【问题标题】:Is population of field with a type of array of ObjId even possiple?具有 Obj 数组类型的字段人口甚至可能吗?
【发布时间】:2018-12-24 05:59:28
【问题描述】:

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

这里是文章模型的一部分

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 调试结果,注意 mongoose 调用文章模型而不是标签来填充标签等类别,因此填充不起作用。

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: {} })

【问题讨论】:

  • 为什么猫鼬叫articles.find而不是tags.find?

标签: mongodb mongoose nosql


【解决方案1】:

是的,这是可能的。

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

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

否则 mongoose 将在父模型而不是子模型上进行查找查询,注意这种方法仅在数组情况下是必需的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多