猫鼬无法从数组中获取所有对象

时间:2018-11-11 10:02:41

标签: node.js mongoose

我有一个猫鼬查询,该查询应获取某些事件模型中的所有参与者,但我只能找回一个参与者。我尝试了$all方法,仍然没有结果。

查询:

Participants.find({'_id': {$all: event.participants}}, (err, participants) => {
    if (err) {
      return console.log(err);
    }
    console.log(participants);
});

输出:

 [ { createdAt: 1970-01-01T00:00:00.011Z,
_id: 5be7fc340016817bcb4ybdfc,
name: 'TEST',
ticket: 5be7fc340016817bc44fbdfb,
email: 'test@test.com',
__v: 0 } ]

预期产量

[ { createdAt: 1970-01-01T00:00:00.011Z,
_id: 5be7fc340016817bcb4fbdfc,
name: 'TEST',
ticket: 5be7fc3400d16817bcb4fbdfb,
email: 'rene370d@gmail.com',
__v: 0 }, 
{ createdAt: 1970-01-01T00:00:00.011Z,
_id: 5be7fc340016817bcb4fbdfc,
name: 'Another test',
ticket: 5be7fc3s40016817bcb4fbdfb,
email: 'another@emai.com',
__v: 0 }  ]

event.participants

 participants:{
type: [mongoose.Schema.Types.ObjectId],
ref: 'ParticipantSchema'
}

1 个答案:

答案 0 :(得分:0)

来自documentation

  

$ all运算符选择文档,其中字段的值是包含所有指定元素的数组。

因此,使用它来获取特定模型的所有文档没有太大意义。 而是使用$in运算符

Participants.find({ _id: { $in: event.participants } }, (err, participants) => {
  if (err) {
    return console.log(err);
  }
  console.log(participants);
});