0

I have a object in mongodb. I want to filter their sections using status. If status is active then only that has to be sent to the user.

Structure of the Course schema is:

{
   _id: 'ObjectId',
   name: 'NODE JS',
   .
   .
   sections: [
      {status: 'active', trainer: 'XYZ'}, {status: 'inactive', trainer: 'YZX'}, .....
   ]
}

below 'sections.status': 'active' is working properly for filtering the courses but it is returning all the sections which are not active. How can I filter the array in mongoose query itself. Without handling the query results.

Course.findOne({ _id: req.params.id , 'sections.status': 'active' })
  .exec((err, course) => {
    if (err) {
      logger.error(err);
      res.status(500).json({ success: false, message: 'Error in getting data' });
    } else if (!course) {
      res.status(404).json({ success: false, message: 'No course details found' });
    } else {
      res.json({ success: true, course });
    }
  });
Akhil P
  • 1,580
  • 2
  • 20
  • 29
  • You want the response to contain all the data from the schema with the only difference being that that the inactive `sections` are removed? – Mike Dec 15 '16 at 05:18
  • @Mike Yes. What you said is true. – Akhil P Dec 15 '16 at 05:21
  • I don't believe that you can remove data from a document using Mongoose without writing to the database itself. I think you said you didn't want to do this in your answer but the best you're likely able to do is manually remove items from `sections` that are inactive and send the modified object in the response instead. See here for a reference: http://stackoverflow.com/questions/14504385/why-cant-you-modify-the-data-returned-by-a-mongoose-query-ex-findbyid – Mike Dec 15 '16 at 05:27

1 Answers1

2

You can't have Mongoose return a modified document for you without writing it to the database. However, you can use the lean function to have Mongoose return an object literal, without the added overhead of the full model itself, and modify that object as you wish to send with your data.

Course.findOne({ _id: req.params.id , 'sections.status': 'active' })
  .lean()
  .exec((err, course) => {
    if (err) {
      logger.error(err);
      res.status(500).json({ success: false, message: 'Error in getting data' });
    } else if (!course) {
      res.status(404).json({ success: false, message: 'No course details found' });
    } else {

      // Remove all 'inactive' sections
      course.sections = course
                          .sections
                          .filter((section) => section.status === 'active')

      res.json({ success: true, course });
    }
  });

See the following post for a reference.

Why can't you modify the data returned by a Mongoose Query (ex: findById)

Community
  • 1
  • 1
Mike
  • 3,830
  • 2
  • 16
  • 23