【问题标题】:Moogoose self reference not populate未填充猫鼬自我参考
【发布时间】:2015-01-13 14:36:56
【问题描述】:

我在猫鼬中有一个这样的自我参考:

var wordSchema = new mongoose.Schema({
        content : String,
        country: [{type: mongoose.Schema.Types.ObjectId, ref: 'Country'}],
        trad: {
            words: [{
                _id: { type: mongoose.Schema.Types.ObjectId, ref: 'Word' }

            }]
        }

    });

我想用 find 取回我的模型的属性内容:

 Word.find({ content:regex, country:'5464dcee1874048e2c623389' }).populate('trad.words').exec(function (err, words) {
        if (!err) {
            res.json(words);
        } else {
            console.log(err);
        }
    });

这是我得到的结果:

_id: "5468d91c6481cd063033a4d0"
content: "content"
country: [5464ddd226e63fad2c5aa053]
trad: {words:[{_id:5468d91c6481cd063033a4cf}]}
words: [{_id:5468d91c6481cd063033a4cf}]
0: {_id:5468d91c6481cd063033a4cf}
_id: "5468d91c6481cd063033a4cf"

我不明白为什么它没有在 subDocument 字中返回我其他属性.. 你能帮我理解我做错了什么吗?

谢谢,

马克西姆

【问题讨论】:

    标签: node.js mongoose mongoose-populate


    【解决方案1】:

    有不止一种传统吗?因此,设置路径 populate('countries trad.words') 如下:

    var wordSchema = new mongoose.Schema({
            content : String,
            countries: [{type: mongoose.Schema.Types.ObjectId, ref: 'Country'}],
            trad: [{
                _id: mongoose.Schema.Types.ObjectId,
                words: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Word' }]
            }]
        });
    

    否则,您不需要传统领域。因此,设置路径 populate('countries trad_words') 如下:

    var wordSchema = new mongoose.Schema({
            content : String,
            countries: [{type: mongoose.Schema.Types.ObjectId, ref: 'Country'}],
            trad_words: [{type: mongoose.Schema.Types.ObjectId, ref: 'Word'}]
        });
    

    【讨论】:

    • 非常感谢费尔南多。只是一个小问题:我如何添加一个新的传统呢?我尝试 words.trad.push(traduction);它返回我无法调用未定义的方法“推送”..(基于您向我提出的第一个模式)
    • 现在,定义了您的架构,这很容易。如需更多信息,请查阅此链接:mongoosejs.com/docs/subdocs.html如果无法解决,请在此处重新写。
    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 2020-11-30
    • 1970-01-01
    • 2014-11-01
    • 2013-01-15
    • 2021-05-06
    • 2015-07-13
    • 2016-10-10
    相关资源
    最近更新 更多