Mongoose错误 – elemMatch()必须在使用这些参数调用where()之后使用

我有以下模式:

UserSchema = new Schema({ 'username': { type: String, validate: [validatePresenceOf, 'a username is required'], index: { unique: true } }, 'hashed_password': String, 'salt': String, 'locations': [LocationSchema] }); LocationSchema = new Schema({ 'lat': Number, 'lng': Number, 'address': { type: String, validate: [validatePresenceOf, 'The address is required in order to add a new location.'] }, 'name': String }); 

我试图通过它的idfind一个特定的单个位置文件。 要做到这一点,我试图通过位置文件的数组位置查询用户收集项目。 我的查询如下所示:

 var query = User.find({"locations.$": 1}) .where() .elemMatch({locations: {_id : ObjectId('531283690315992f05bcdc98')}}) .exec(function(err, data){ console.log(err); console.log(data); }); 

当它运行时,我得到以下错误:

错误:在使用这些参数调用where()时,必须使用elemMatch()

这是什么意思? 我似乎无法find一个好的解释。

忘了提及,我可以通过运行以下db.users.find({locations: {$elemMatch : {_id : ObjectId('531283690315992f05bcdc98')}}}, {"locations.$": 1});获取我想要从mongo shell获得的数据: db.users.find({locations: {$elemMatch : {_id : ObjectId('531283690315992f05bcdc98')}}}, {"locations.$": 1});

你需要提供一个path给你的通话并重新sorting:

 User.find() .where('locations') .elemMatch({_id : ObjectId('531283690315992f05bcdc98')}) .select({'locations.$': 1}) .exec(function(err, data){ console.log(err); console.log(data); }); 

但是你也可以简化它,因为你不需要在这里使用$elemMatch ,你可以让Mongoose照顾铸件:

 User.find() .where('locations._id', '531283690315992f05bcdc98') .select({'locations.$': 1}) .exec(function(err, data){ console.log(err); console.log(data); });