Mongoose对面填充一个数组

问题描述 投票:0回答:2

列表可以包含许多项目。我可以轻松地从列表中检索所有项目,但我遇到了相反的问题,即检索包含项目的所有列表

ItemSchema:

const ItemSchema = mongoose.Schema({
  name: { type: String, required: true, min: 1 },
  created_at: { type: Date, default: Date.now }
},{ toJSON: { virtuals: true }});

ListSchema:

const ListSchema = mongoose.Schema({
  title: { type: String, required: true, max: 100 },
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  description: { type: String, required: true },
  items: [{
      type: mongoose.Schema.Types.Mixed, ref: 'Item', quantity: 'String'
  }],
  completed: { type: Boolean, default: false },
  date: { type: Date, default: Date.now },
});

文献:

"items": [
    {
       "_id": "5c6d74a98a3f532b4c1d2a23",
       "quantity": "7"
    }
],

我如何填充:Item.findById(id).populate('lists');但它返回空数组。

有什么建议?

node.js mongoose schema virtual populate
2个回答
0
投票

我有更改请检查它,让我在填充中的list

Item.findById(ID).populate( '量')

或者你可以使用它

const product = await Item.findOne({_id: id}).populate('quantity');
console.log("populate result...",product.quantity)

0
投票

很长一段时间没有使用过MongoDB,但似乎你的项目模式中没有“list”键可以首先填充。也许你应该添加一个或查询具有该项目的列表。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.