Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

node.js - Mongoose :Find and filter nested array

I'm trying to find a whole document with Find() command and filter a nested array with a condition.

Here a piece of the used Schema :

var ListSH = new Schema({
  name: { type: String, unique: true, required: true},
  subject : String,
  recipients : [
    Schema({
     uid : { type : ObjectId, required : true, ref:'User', unique: true},
     status : { type : Number, default : 1 }
     },{_id: false})
  ]
};

Currently I do ListModel.findOne({ _id : req.params.id_list, function(err,list){...};

And Postman give me that:

{
  "_id": "57e6bcab6b383120f0395aed",
  "name": "Emailing listname",
  "subject": "List subject",
  "recipients": [
    {
      "uid": "57e932bcbbf0e9e543def600",
      "status": 0
    },
    {
      "uid": "57e93266c3c0b1dc1625986f",
      "status": 1
    }
  ]
}

I'd like Postman to return me something like that by adding a recipients.status : 1 condition

  {
      "_id": "57e6bcab6b383120f0395aed",
      "name": "Emailing listname",
      "subject": "List subject",
      "recipients": [
        {
          "uid": "57e93266c3c0b1dc1625986f",
          "status": 1
        }
      ]
    }

I've already tried ListModel.findOne({ _id : req.params.id_list, 'recipients.status' : 1}, function(err,list){...};

and something weird like populate([$match('recipients.status : 1)]); but with no success..

Anyone knows ? Thanks ^^

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try below query:

ListModel.findOne({"_id" : "57e6bcab6b383120f0395aed", 'recipients.status' : 1},{_id:1, name: 1, subject:1,'recipients.$': 1}, function(err,list){...});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...