如何填充模式mongodb中的嵌套字段

k2fxgqgv  于 2022-12-29  发布在  Go
关注(0)|答案(2)|浏览(161)

我有一个结构如下的摘要模式

{
    sender: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    summary: {
      type: String,
    },
    sent: {
      type: Date,
      default: Date.now,
    },
  }
);

那么convo模式:注意:此模式中的summary是一个objectId数组,convo在获取后返回一个对象数组,sender位于填充summary字段后获得的每个对象中

{
    lastMessage: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "messages",
    },
    members: {
      type: [mongoose.Schema.Types.ObjectId],
      ref: "User",
      required: true,
    },
    summary: {
      type: [mongoose.Schema.Types.ObjectId],
      ref: "summary",
    },
    gigDetails: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Gig",
    },
  }

除了已经填充的summary字段之外,我还想在convo模式的summary数组中填充sender字段。我该怎么做呢?

oprakyz7

oprakyz71#

你可以这样做:

ConvoModel.find(filter).populate([{ path: 'summary', populate: { path: 'sender' } }])
ev7lccsx

ev7lccsx2#

// Fetch the convo documents
const convos = await Convo.find()
  .populate("summary")
  .exec();

// Iterate through the convos array
for (let i = 0; i < convos.length; i++) {
  // Iterate through the summary array and populate the sender field in each element
  const summaryPromises = convos[i].summary.map(async summary => {
    return await summary.populate('sender').execPopulate();
  });

  // Wait for all promises to resolve
  await Promise.all(summaryPromises);
}

相关问题