-1

I have schema:

{
  name: String,
  surname: String,
  note: String,
  someField: String,
  secondSomeField: String
  blackList: [{
     userId: mongoose.Types.ObjectId,
     reason: String
  }]
}

I need select document with all fields, but in blackList field I need select only userId. Example what I want:

{
      name: "John",
      surname: "Doe",
      note: "bwrewer",
      someField: "saddsa",
      secondSomeField: "sadsd",
      blackList: [58176fb7ff8d6518baf0c931, 58176fb7ff8d6518baf0c932, 58176fb7ff8d6518baf0c933, 58176fb7ff8d6518baf0c934]
}

How I can do this? When I do

Schema.find({_id: myCustomUserId}, function(err, user) {
      //{blackList: [{userId: value}, {userId: value}]}
      //but i need
      //{blackList: [value, value, value]}
})
halfer
  • 19,824
  • 17
  • 99
  • 186
Jackson
  • 884
  • 2
  • 13
  • 22
  • It's answer : `Schema.aggregate( {$match: {_id: mongoose.Types.ObjectId(myCustomId)} }, {$project: {blackList: "$blackList.userId", name: true, surname: true, someField: true}} ).exec(fn)` – Jackson Dec 02 '16 at 21:24

2 Answers2

1

If you want to hide the field by default:

{
  name: String,
  surname: String,
  note: String,
  someField: String,
  secondSomeField: String
  blackList: [{
     userId: mongoose.Types.ObjectId,
     reason: {type:String, select:false}
  }]
}

If you simply want to exclude in that query:

Schema
    .find({_id: myCustomUserId})
    .select("-blackList.reason")
    .exec(function (err, user) {
      //your filtered results
})

Not tested but they should work both.

alfredopacino
  • 2,979
  • 9
  • 42
  • 68
  • I didnot test, but I tested a similar query, and result was: `blackList: [{userId: id}, {userId: id}]` but I need: `[id, id, id]`, becouse i will exec next query: `Schema.find({_id: {$nin: arrayOfIds}})` – Jackson Dec 02 '16 at 00:44
  • You can keep the first query in this way and edit the next query using `$elemMatch`. See this answer http://stackoverflow.com/questions/14040562/how-to-search-in-array-of-object-in-mongodb – alfredopacino Dec 02 '16 at 10:01
  • elemMatch - for search in array, it's not help for me. I need search users, who are not in my blackList – Jackson Dec 02 '16 at 19:02
  • i try query alfredopacino, It's not work( result is: blackList: [{userId: id}, {userId: id}] (( – Jackson Dec 02 '16 at 19:09
0
Schema.aggregate( {$match: {_id: mongoose.Types.ObjectId(myCustomId)} }, {$project: {blackList: "$blackList.userId", name: true, surname: true, someField: true}} ).exec(fn)
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
Jackson
  • 884
  • 2
  • 13
  • 22