【问题标题】:How to populate a document inside an array inside another document?如何在另一个文档中的数组中填充文档?
【发布时间】:2019-01-26 20:01:58
【问题描述】:

对不起,如果标题看起来很复杂...我想不出更好的方式来描述它。

我的真实案例情况符合以下方案:

收藏1

const mongoose = require('mongoose');

const itemSchema = mongoose.Schema({
  _id:         mongoose.Schema.Types.ObjectId,
  name:        { type: String, required: [true, 'Name is required.'] },
  quantity:    { type: Number, required: [true, 'Quantity is required.'] },
  collection2: { type: mongoose.Schema.Types.ObjectId, ref: 'Collection2' }
}, { _id : false });

const collection1Schema = mongoose.Schema({
  _id:          mongoose.Schema.Types.ObjectId,
  name:         { type: String, required: [true, 'Name is required.'] },
  imagePath:    { type: String, required: [true, 'Image is required.'] },
  items:        [itemSchema]
});

module.exports = mongoose.model('Collection1', collection1Schema);

注意:itemsSchema 位于 collection1 文件中(并且具有 no 声明的 _id),因为它们仅存在于 Collection1 模型中(考虑到“数量”和我为简化而删除的其他字段)。这个 itemsScheme 在其他地方不需要作为另一个集合。

Collection2

const mongoose = require('mongoose');

const collection2Schema = mongoose.Schema({
  _id:    mongoose.Schema.Types.ObjectId,
  name:   { type: String, required: [true, 'Name is required.'], unique: true }
});

module.exports = mongoose.model('Collection2', collection2Schema );

注意:为简化起见,删除了其他属性(例如“imagePath”)。

现在,这是我要运行的查询:

Collection1.find()
 .populate({
   path: 'items',
   populate: {
     path: 'collection2', model: 'Collection2'
   }
 })
 .then(...)
 .catch(...);

这是我运行它时收到的错误消息:

Error fetching collection1:  Cast to ObjectId failed for value "{
  name: 'an item name',
  quantity: 750
}" at path "_id" for model "Collection1"

如果我只是运行,就会发生完全相同的错误:

Collection1.find()
 .populate('items')
 .then(...)
 .catch(...);

也许我无法运行.populate('items'),因为它没有声明的模型。如果是这种情况,我如何在查询 collection1 时填充 collection2?同样,我不能考虑将项目存储在单独的集合中。

但如果我跑:

Collection1.find()
 .populate('collection2')
 .then(...)
 .catch(...);

我得到了项目,没有错误,但它没有填充 collection2。好吧,这对项目来说是有意义的,因为它们只是 collection1 中的一组属性的数组。但是填充 collection2 呢?

Collection2 已经添加了一些文档,所有文档的 _id 和其他字段都填写得很好。在控制器中,我设置了_id: new mongoose.Types.ObjectId(),同时为Collection1 和Collection2 这两种情况创建了一个新文档。

在前端,我为 Collection1 创建了一个新文档,我添加了项目,每个项目都有一个来自 Collection2 的文档,并且我保存了所有内容,没有错误。我还确认所有内容都已正确保存(collection1 有项目列表,每个项目都有一个对 collection2 的 _id 引用)。唯一的问题是在这个数组中填充 collection2。

我已经尝试使用 _ids(包括 itemScheme)重组所有内容并删除所有集合以再次测试它,但没有成功。

我已经被这个问题困扰了大约三天了。

我应该为 populate 设置任何特殊属性以使其适用于这个特定结构吗?

提前谢谢...

【问题讨论】:

    标签: node.js typescript mongoose mongoose-schema populate


    【解决方案1】:
    populate('items')
    

    这将不起作用,因为 item 不是模型。

    你想要的如下:

    Collection1.find()
     .populate('items.collection2')
     .then(...)
     .catch(...);
    

    这将在所有数组元素中填充 collection2

    【讨论】:

    • 像魅力一样工作! ^^
    猜你喜欢
    • 2020-03-07
    • 2016-04-13
    • 2015-10-31
    • 2021-04-24
    • 2020-12-18
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多