【问题标题】:Mongoosejs find on array of objectIdMongoosejs 在 objectId 数组上找到
【发布时间】:2015-04-20 07:41:06
【问题描述】:

我从几个小时以来一直在努力解决这个问题,因此在这里发布。我正在尝试在 mongoose 中使用 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[],它包含 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("----------------------");

    }

这两个似乎都不起作用。谢谢你的帮助。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

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

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

    【讨论】:

    • 这仍然没有获取任何结果。它返回一个空数组
    • 这看起来像正确的语法。您确定集合中存在具有正确B _idA 数组吗?如果您在 mongo shell 中尝试类似的查询会发生什么?
    • 啊..对不起。 .这行得通。事实证明我使用了错误的 ID。原谅我的无知。实际上,我们甚至不需要转换为 ObjectId 即可工作。
    猜你喜欢
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 2014-10-10
    • 2023-03-06
    • 2016-04-30
    相关资源
    最近更新 更多