nov*_*von 1 mongoose mongodb node.js express
我有以下架构:
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
});
Run Code Online (Sandbox Code Playgroud)
我正试图通过它的id找到一个特定的单一位置文档.为此,我尝试按位置键查询用户集合项,位置键是位置文档的数组.我的查询如下所示:
var query = User.find({"locations.$": 1})
.where()
.elemMatch({locations: {_id : ObjectId('531283690315992f05bcdc98')}})
.exec(function(err, data){
console.log(err);
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
当它运行时,我收到以下错误:
错误:在使用这些参数调用where()之后,必须使用elemMatch()
这是什么意思?我似乎无法找到一个好的解释.
忘了提一下,我可以通过运行以下命令从mongo shell获取我想要的数据: db.users.find({locations: {$elemMatch : {_id : ObjectId('531283690315992f05bcdc98')}}}, {"locations.$": 1});
您需要提供where呼叫路径并重新排序:
User.find()
.where('locations')
.elemMatch({_id : ObjectId('531283690315992f05bcdc98')})
.select({'locations.$': 1})
.exec(function(err, data){
console.log(err);
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
但你也可以稍微简化一下,因为你不需要在$elemMatch这里使用,你可以让Mongoose负责投射:
User.find()
.where('locations._id', '531283690315992f05bcdc98')
.select({'locations.$': 1})
.exec(function(err, data){
console.log(err);
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1380 次 |
| 最近记录: |