在查询中遇到困难,我有一组用户:
{
"_id": "5c87bda25fdaasdf00171001e1",
"name": "UserTwo Name",
"email": "email2@example.com"
},{
"_id": "5c87bda25fda8b00171001e1",
"name": "User Name",
"email": "email@example.com"
}
我还有一个包含 _userId 键的对象数组。我需要获取用户 _id 等于数组中 _userId 值的所有用户。
[
{_userId: "5c87bda25fda8b00171001e1"},
{_userId: "5c87bda25fdaasdf00171001e1"},
]
到目前为止我所拥有的是:
User.find(
{
_id: { $in: req.body.users }
}
)
如果 req.body.users 只是一个 ids 数组,而不是对象数组,那应该没问题。
任何帮助将不胜感激。 谢谢,
最佳答案
您应该像这样修改您的查询:
User.find({
_id: { $in: req.body.users.map(user => ObjectId(user._userId) }
});
您需要将 _userId 字符串转换为 ObjectId。这将通过 map
函数来完成。
关于node.js - MongoDB、Mongoose 查找所有 _id 等于数组中对象键的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55159716/