gpt4 book ai didi

node.js - Mongoose 错误 - 使用这些参数调用时,必须在 where() 之后使用 elemMatch()

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:37 25 4
gpt4 key购买 nike

我有以下架构:

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
});

我正在尝试通过 id 查找特定的单个位置文档。为此,我尝试通过位置键(位置文档数组)查询用户集合项。我的查询如下所示:

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

console.log(err);
console.log(data);
});

运行时出现以下错误:

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

这是什么意思?我似乎找不到很好的解释。

忘了提及,我可以通过运行以下命令从 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);
});

但是您也可以稍微简化一下,因为您不需要在此处使用 $elemMatch 并且可以让 Mongoose 负责转换:

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

关于node.js - Mongoose 错误 - 使用这些参数调用时,必须在 where() 之后使用 elemMatch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22123554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com