首页 > 解决方案 > 无法将对象添加为另一个现有 JSON 对象的子字段

问题描述

我无法添加以下对象:

[
    { 'option1':'opt1','option2':'opt2','option3':'opt3'},
]

作为提交给:

const question_list=await Questions.find({ $and: [{categoryid:categoryId},{ isDeleted: false }, { status: 0 }] }, { name: 1 });

question_list=[{"_id":"5eb167fb222a6e11fc6fe579","name":"q1"},{"_id":"5eb1680abb913f2810774c2a","name":"q2"},{"_id":"5eb16b5686068831f07c65c3","name":"q5"}]

我希望最终的对象是:

[{"_id":"5eb167fb222a6e11fc6fe579","name":"q1","options":[
    { 'option1':'opt1','option2':'opt2','option3':'opt3'},
]},{"_id":"5eb1680abb913f2810774c2a","name":"q2","options":[
    { 'option1':'opt1','option2':'opt2','option3':'opt3'},
]},{"_id":"5eb16b5686068831f07c65c3","name":"q5","options":[
    { 'option1':'opt1','option2':'opt2','option3':'opt3'},
]}]

什么是最好的解决方案?

标签: mongodbmongoosemongodb-queryaggregation-framework

解决方案


您需要使用聚合管道来执行此操作,而不是.find(). 由于投影.find()只能接受$elemMatch, $slice, and $现有字段:project-fields-from-query-results。因此,要在文档中添加包含新数据的新字段,请$project在聚合框架中使用。

const question_list = await Questions.aggregate([
  {
    $match: {
      $and: [{ categoryid: categoryId }, { isDeleted: false }, { status: 0 }]
    }
  },
  {
    $project: {
      _id: 0,
      name: 1,
      options: [{ option1: "opt1", option2: "opt2", option3: "opt3" }]
    }
  }
]);

测试: mongoplayground


推荐阅读