0

I want to include and exclude some fields if specific condition in query.

// Survey Schema:
new mongoose.Schema({
    options: {
        type: [mongoose.Schema.Types.String]
    },
    votes: {
        type: [{
            user: mongoose.Schema.Types.ObjectId,
            option: mongoose.Schema.Types.Number,
        }]
    },
})

And I want some like this in my route handler.

const userID = req.user.id
const isAuth = userID!=undefined

const surveys = await Survey.aggregate([
    $project:{
       options:1,
       votes: {
          $cond: {
            if: {
                 $in: [user.id, 'votes']
            }
          }
       }  
    }
])

And the result should be

if userID is in the array votes for the specific document in the snapshot, the fields should be

{options:[], votes:[]},...

else

{options:[]},...

1 Answers1

1

If userID is undefined then set votes to 0.

let project = {};

if (!userID) {
    project.votes = 0;
}

const surveys = await Survey.find({}, project);
Shihab
  • 2,641
  • 3
  • 21
  • 29