猫鼬populate()返回空数组 [英] Mongoose populate() returning empty array

查看:234
本文介绍了猫鼬populate()返回空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我已经花了大约4个小时,多次阅读文档,但仍然无法弄清我的问题.我正在尝试对我的模型做一个简单的populate(). 我有一个用户模型和商店模型.用户有一个favoriteStores数组,其中包含商店的_id.我要寻找的是将使用商店详细信息填充此数组.

so I've been at it for like 4 hours, read the documentation several times, and still couldn't figure out my problem. I'm trying to do a simple populate() to my model. I have a User model and Store model. The User has a favoriteStores array which contains the _id of stores. What I'm looking for is that this array will be populated with the Store details.

user.model

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);
    });
}

另一个文件:

store.model

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 running this what I get is:

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

即使我只是在没有填充的情况下获取商店时,favouriteStores还是空的,它确实显示了商店的_id.

The favoriteStores is empty, even though when I just do a get of the stores without the populate it does display the _id of the store.

任何帮助将不胜感激!谢谢;)

Any help is greatly appreciated! Thanks ;)

更新 使用 deepPopulate插件后,它神奇地修复了它.我猜问题出在userSchema的嵌套上.仍然不确定问题到底出在什么地方,但至少已经解决了.

UPDATE After using the deepPopulate plugin it magically fixed it. I guess the problem was with the nesting of the userSchema. Still not sure what the problem was exactly, but at least it's fixed.

推荐答案

我认为跨多个文件定义架构时会发生此问题.要解决此问题,请尝试通过以下方式调用populate:

I think this issue happens when schemas are defined across multiple files. To solve this, try call populate this way:


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

这篇关于猫鼬populate()返回空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆