【发布时间】:2021-10-13 04:44:24
【问题描述】:
我对 mongoose 查询有一个小问题。
我需要获取一个唯一基于具有 2 ObjectId 的数组的文档
字段。它是独一无二的,因为它只会在一个文档中匹配成员对
我需要匹配 members 中的两个 ObjectId,然后获取文档
这是我的路线:
router
.route('/convWith/:firstUser/:secondUser')
.get(protect, myConversationWithUser);
这是我的控制器查询:
const conversation = await Conversation.findOne({
members: { $all: [req.params.firstUser, req.params.secondUser] },
});
架构
const conversationSchema = new mongoose.Schema(
{
members: {
type: Array,
},
},
{ timestamps: true }
);
const Conversation = mongoose.model('Conversation', conversationSchema);
module.exports = Conversation;
我的两个参数都正确,但 findOne 函数返回 null,它不应该。我在这里做错了什么?非常感谢!
【问题讨论】:
-
你能展示你的架构吗?
-
当然,我刚刚用我的对话模式更新了帖子
-
您需要将输入 id 从字符串转换为 objectId
[mongoose.Types.ObjectId(req.params.firstUser), mongoose.Types.ObjectId(req.params.secondUser)],因为您没有在 schema 的 members 数组中指定任何类型。 -
天哪,真是个愚蠢的错误!谢谢你兄弟为我发现了这一点。
标签: node.js mongodb mongoose mongodb-query