Ano*_*oop 3 javascript mongoose mongodb node.js
我现在几个小时就一直在努力,因此在这里张贴.我试图在mongoose中使用find()运算符来查找键是否匹配数组中的任何单个元素,类似于如何在Mongoose中执行id数组查询?但没有得到预期的结果.
这是我的架构,
var a = new mongoose.Schema({
b : { type : mongoose.Schema.ObjectId, ref: 'B' },
});
var A = mongoose.model('A', a);
Run Code Online (Sandbox Code Playgroud)
现在我有一个数组,arr [],它包含了B类的一些可能的对象id
arr = ["54e545fb6a0d90bb0772808b", "xxxxxxxxxxxxx", ...]
Run Code Online (Sandbox Code Playgroud)
我想找到类型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("----------------------");
}
Run Code Online (Sandbox Code Playgroud)
这两个似乎都不起作用.感谢您的帮助.
Yur*_*bin 11
假设arr是一个表示ObjectId的字符串数组:
A.find({b : {
$in: arr.map(function(o){ return mongoose.Types.ObjectId(o); })
}}, callback);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8106 次 |
| 最近记录: |