1

I am unable to add the following object:

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

as a sub filed to:

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"}]

I want the final Object to be as:

[{"_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'},
]}]

what is the best possible solution?

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46

1 Answers1

0

You need to use aggregation-pipeline to do this, instead of .find(). As projection in .find() can only accept $elemMatch, $slice, and $ on existing fields : project-fields-from-query-results. So to add a new field with new data to documents, use $project in aggregation framework.

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" }]
    }
  }
]);

Test : mongoplayground

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
  • I am getting the options field added,but the match operator is not working I am getting null set even I am Having matching Data – rocker-hacker May 05 '20 at 15:17
  • @AbhinavV : Using playground link can you give me sample docs & input, let's try like that !! – whoami - fakeFaceTrueSoul May 05 '20 at 15:28
  • Surprisngly ur query answer was working in mongoplayground but im unable to use the same code in nodejs https://mongoplayground.net/p/_WJGsFZjpc_ what could be the error – rocker-hacker May 05 '20 at 15:36
  • @AbhinavV : that I'm not sure, try to debug by printing incoming request, One common mistake usually people is with type match, Let's say if `categoryid` is of type `ObjectId()` & input will usually be string then it doesn't get you anything as there is type mismatch, So you need to convert string to ObjectId() prior to querying.. – whoami - fakeFaceTrueSoul May 05 '20 at 15:44
  • yes that was the issue,So is there any built in mongoose method to convert a string to ObjectId() – rocker-hacker May 05 '20 at 16:33
  • @AbhinavV : Check this : (https://stackoverflow.com/questions/6578178/node-js-mongoose-js-string-to-objectid-function) – whoami - fakeFaceTrueSoul May 05 '20 at 16:33