AFAF
AFAF

Reputation: 599

MongoDB - find only elements with boolean false from Schema model

I'm unsing MongoDB and NodeJS and I'm trying to find all tasks with done: false to display on Dashboard. I'm sorting by the newest to oldest and with a limit of 4 to send and display, but it's sending all tasks and I want that send only with the done: false (this means the tasks are not checked:done:true) but I don't know how to put that in options of populate..

my Tasks Schema model:

let mongoose = require("mongoose");

let taskSchema = new mongoose.Schema({

    tasktitle: String,
    taskcomment: String,
    project: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Project'
    }],
    user: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }],
    created: {
        type: Date,
        default: Date.now
    },
    done: {
        type: Boolean,
        default: false
    }
})

module.exports = mongoose.model('Tasks', taskSchema);

my Tasks Controller:

exports.render_pending_tasks = (req, res) => {
let userid = req.user._id;

  User.findById(userid).populate({ path: 'tasks', options: { sort: { _id: -1 }, limit: 4 } })
      .exec((err, tasks) => {
         if (err) {
             console.log(err);
            } else {
                res.send(tasks);
            }
        });
};

Upvotes: 1

Views: 565

Answers (1)

Ashh
Ashh

Reputation: 46481

You can use match option inside the populate function

User.findById(userid)
 .populate({
  match: { done: false },
  path: 'tasks',
  options: { sort: { _id: -1 }, limit: 4 }
})

Upvotes: 1

Related Questions