Mongoose populate () returns an empty array

therefore, I was on it for 4 hours, read the documentation several times and still could not understand my problem. I am trying to make simple populate () for my model. I have a user model and a store model. The user has an array of favoriteStores that contains _id stores. I am looking for this array to be populated with store data.

user.model

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var UserSchema = new Schema({
      username: String,
      name: {first: String, last: String},
      favoriteStores: [{type: Schema.Types.ObjectId, ref: 'Store'}],
      modifiedOn: {type: Date, default: Date.now},
      createdOn: Date,
      lastLogin: Date
});

UserSchema.statics.getFavoriteStores = function (userId, callback) {
    this
    .findById(userId)
    .populate('favoriteStores')
    .exec(function (err, stores) {
        callback(err, stores);
    });
}

And one more file:

store.model

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var StoreSchema = new Schema({
  name: String,
  route: String,
  tagline: String,
  logo: String

});

module.exports = mongoose.model('Store', StoreSchema);

After doing this, I get:

{
    "_id": "556dc40b44f14c0c252c5604",
    "username": "adiv.rulez",
    "__v": 0,
    "modifiedOn": "2015-06-02T14:56:11.074Z",
    "favoriteStores": [],
    "name": {
        "first": "Adiv",
        "last": "Ohayon"
    }
}

Favorite stores are empty, although when I just shop from stores without filling, it displays _id in the store.

Any help is much appreciated! Thank;)

UPDATE deepPopulate plugin . , userSchema. , , , , .

+1
1

, , . , populate :

.populate({path: 'favoriteStores', model: 'Store'})
0

Source: https://habr.com/ru/post/1683153/


All Articles