猫鼬 findOne 数组的 ObjectId returns 空

Mongoose findOne array of ObjectId returns null

使用 ObjectId 数组执行 findOne 查询时遇到一些问题。简化架构如下:

型号:

var InboxSchema = new Schema({
    _users: [
        {
            type: mongoose.Schema.ObjectId,
            ref: 'User',
            required: 'Users are required',
            unique: true
        }
    ]
}

mongoose.model('Inbox', InboxSchema)

查询:

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

收件箱总是 returns null,尽管它在使用 Mongo shell 时返回了一些东西,所以我知道我的查询有效。以前,我只查询 userIds,后来我意识到这不起作用,因为我必须使用 ObjectId 进行查询。但是,即使将字符串转换为 ObjectId 也不起作用。

尝试使用 mongo 数组查询运算符 $all or $in

$all 将目标匹配到所有数组元素:

Inbox.findOne({ "_users": { "$all": users} }).exec(function (err, inbox) {
    console.log(inbox);
})

$in 将目标与任何数组元素匹配:

Inbox.findOne({ "users": { "$in": users} }).exec(function (err, inbox) {
    console.log(inbox);
})