[英]Mongoose findOne array of ObjectId returns null
Having some issues performing a findOne query with an array of ObjectIds. 在使用ObjectId数组执行findOne查询时遇到一些问题。 Simplified schema as follows: 简化的架构如下:
Model: 模型:
var InboxSchema = new Schema({
_users: [
{
type: mongoose.Schema.ObjectId,
ref: 'User',
required: 'Users are required',
unique: true
}
]
}
mongoose.model('Inbox', InboxSchema)
Query: 查询:
var users = [];
var userIds = ['5567ead844997f969fe3f00f', '558b8492f1723b090b414765'];
for (var i=0; i<userIds.length; i++) {
users.push(new mongoose.Types.ObjectId(userIds[i]));
}
Inbox.findOne({_users: users}).exec(function (err, inbox) {
console.log(inbox);
}
Inbox always returns null despite it returning something when using Mongo shell, so I know that my query works. 尽管使用Mongo Shell时收件箱返回了某些内容,但Inbox始终返回null,因此我知道查询有效。 Previously, I was querying on just userIds
alone, which I later realised was not working as I would have to query using ObjectId. 以前,我只查询userIds
,后来我意识到它无法正常工作,因为我必须使用ObjectId进行查询。 However, even converting the strings to ObjectId doesn't work. 但是,即使将字符串转换为ObjectId也不起作用。
Try using the mongo array query operators $all
or $in
. 尝试使用mongo数组查询运算符$all
或$in
。
$all to match a target to all of the array elements: $ all将目标与所有数组元素匹配:
Inbox.findOne({ "_users": { "$all": users} }).exec(function (err, inbox) {
console.log(inbox);
})
$in to match a target to any of the array elements: $ in使目标与任何数组元素匹配:
Inbox.findOne({ "users": { "$in": users} }).exec(function (err, inbox) {
console.log(inbox);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.