簡體   English   中英

搜索和查找嵌套在多個對象中的 arrays

[英]Search and lookup arrays nested in multiple objects

我找到與我的數組中的 ID 匹配的所有websites ,在以下情況下,它是兩個網站。 然后,我想查看這些網站的每個conversations arrays 並在名為conversations的不同集合中搜索與這些 ID 匹配的對話。 然后,我想從這些對話中獲取部分/所有字段,並將其添加到我已經擁有的 JSON 文檔中,按每個網站內的對話對它們進行分組。 我一直在玩聚合、放松和分組,但似乎什么都做不了。

router.post('/staffLoadUpTwo', async (req, res) => {
  var userId = '5e8f964a9c2d0780c0163825';

  const company = await Company.findOne({ 'roles.admins': userId });
  var unwrappedCompany = JSON.parse(JSON.stringify(company));

  console.log(unwrappedCompany.websites);

  const website = await Website.find({
    _id: { $in: unwrappedCompany.websites },
  });

  // const unwindTest = await Website.aggregate([{$unwind : "$conversations"}]);

  console.log(website);
});

控制台.log(網站);

[ { conversations: [ '5e90d9ceb089812c9ba1a67b', '5e8f5a6a2582bf629998c3fd' ],
    _id: 5e949cc02483c0c0056a1a98,
    domain: 'http://x.com',
    __v: 0 },
  { conversations: [ '5e8e23595ce6d611cec5033f', '5e8e3afee8e95e1ff94650d3' ],
    _id: 5e949ce8f53450c0341b36cd,
    domain: 'http://y.com',
    __v: 0 } ]

理想output

[{
  _id: "5e949cc02483c0c0056a1a98",
  domain: 'http://x.com'
  conversations: [
    {conversationId: "5e90d9ceb089812c9ba1a67b", messages: {messageArray: ['a'], timeSent: 2}},
    {conversationId: "5e8f5a6a2582bf629998c3fd", messages: {messageArray: ['b'], timeSent: 6}}
]
}
  _id: "5e949ce8f53450c0341b36cd",
  domain: 'http://y.com'
  conversations: [
   {conversationId: "5e8e23595ce6d611cec5033f", messages: {messageArray: ['c'], timeSent: 1}},
   {conversationId: "5e8e3afee8e95e1ff94650d3", messages: {messageArray: ['d'], timeSent: 8}}
]
}]

您不必對 MongoDB 聚合感到壓力。 由於您使用的是 Mongoose,因此您可以輕松地使用 mongoose 填充來實現您在問題中描述的結果。

如果您已將網站方案定義為如下所示:

const websiteSchema = {
  // ...schema definition for other properties
  /* Note the ref property used below, the value must be the name of the
    conversation model, i.e the stringValue you passed into 
    mongoose.model(<stringValue>, conversationSchema); */
  conversations: [ { type: mongoose.Types.ObjectId, ref: 'Conversations' } ]
}

像這樣的 mongoose 查詢:

const website = await Website.find({
    _id: { $in: unwrappedCompany.websites },
  }).populate('conversations');

將 output 填充其會話字段的網站文檔數組,即,您將獲得實際的會話文檔,而不僅僅是他們的_id。

更多關於 ZCCADCDEDB567ABAE643E15DCF0974E503Z 的信息請在此處填寫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM