猫鼬查找返回空数组



我有mongoDB文档,看起来像这样:

{
"_id": {
"$oid": "5b99247efb6fc01dae438815"
},
"participants": [
"5b758a8341ee61f049ded486",
"5b94fb4ffb6fc01dae40eae3"
]
}

猫鼬中的文档模式是这样定义的

var conversationSchema = new mongoose.Schema({
participants: [{ type: mongoose.Schema.ObjectId, ref: 'User'}],
});

我正在获取这样的数据

var ccc = Conversation.find({participants : "5b758a8341ee61f049ded486"});
ccc.exec(function(err, conversations){
res.status(200).json(conversations);
});

问题是我得到一个空数组响应[]

我认为问题出在架构上,但我无法弄清楚如何使其工作。

编辑 如果我将我的架构更改为以下内容,它将起作用:

var conversationSchema = new mongoose.Schema({
participants: [{ type: String}],
});

但我想使用mongoose.Schema.ObjectId而不是Strings作为外键。

尝试将类型添加到此行:

participants: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User'}]

它不会识别数组中的项目,因为它们是字符串,您应该有一个像 {"$oid"这样的对象:"585bb0086c57cd2265b1cbd3"},因此请在 db 中重新插入项目并重试。

最新更新