具有ObjId数组类型的字段填充是否可能?

时间:2018-08-27 12:27:24

标签: mongodb mongoose nosql

在尝试填充标签和类别字段时,我遇到了这种有线行为。

这是文章模型的一部分

tags: {
    type: [mongoose.Schema.Types.ObjectId],
    index: true,
    ref: 'tag'
},

categories: {
        type: [mongoose.Schema.Types.ObjectId],
        index: true,
        ref: 'category'
    }

通过尝试填充这三个字段,只有作者才能工作,因为它不是对象的错位

    .populate('author')
    .populate('tags')
    .populate('categgories')

查看猫鼬的调试结果,请注意,猫鼬正在调用文章模型而不是标签来填充标签,因此类别无法工作。

Mongoose: users.find({ _id: { '$in': [ ObjectId("5b83eacb51e2d33dd5c057ad") ] } }, { fields: { name: 1 } })
Mongoose: articles.find({ _id: { '$in': [ ObjectId("5b83eac851e2d33dd5c057ab") ] } }, { fields: { _id: 1 } })
Mongoose: articles.find({ _id: { '$in': [ ObjectId("5b83eac951e2d33dd5c057ac") ] } }, { fields: {} })

1 个答案:

答案 0 :(得分:0)

是的。

但是您需要告诉猫鼬要搜索哪个模型

populate({path:"path",model:"model"})

否则,猫鼬会在父模型而不是子模型上命中find查询,并指出仅在数组情况下才需要这种方法