Mongoosejs 在 objectId 数组上查找

Mongoosejs find on array of objectId

几个小时以来我一直在努力解决这个问题,因此在这里发帖。我正在尝试在猫鼬中使用 find() 运算符,以查找键是否与数组中的任何单个元素匹配,类似于 How do I perform an id array query in Mongoose? 但未获得预期结果。

这是我的架构,

var a = new mongoose.Schema({
    b : { type : mongoose.Schema.ObjectId, ref: 'B' },
});

var A = mongoose.model('A', a);

现在我有一个数组 arr[],它包含 class B 的一些可能的对象 ID。即

arr = ["54e545fb6a0d90bb0772808b", "xxxxxxxxxxxxx", ...]

我想查找所有类型为 A 的文档,其中字段 b 与 arr 中的任何元素匹配。请注意,arr 是一个字符串数组,但 b 包含 ObjectId。

到目前为止我已经尝试过了,

A.find({b : {$in: arr}}, callback); //and
A.find({b : {$in: new ObjectId("54e545fb6a0d90bb0772808b")}}, callback); //manually got this one value from db

var callback = function (err, data) {
        console.log("----------------------");
        if (err)
            console.log(err);
        else {
            console.log(JSON.stringify(data, null, '\t'));
        }
        console.log("----------------------");

    }

这两个好像都不行。谢谢你的帮助。

假设 arr 是表示 ObjectId 的字符串数组:

A.find({b : {
  $in: arr.map(function(o){ return mongoose.Types.ObjectId(o); })
}}, callback);