MLW*_*DEV 1 mongoose mongodb node.js
在查询中遇到困难,我有一组用户:
{
"_id": "5c87bda25fdaasdf00171001e1",
"name": "UserTwo Name",
"email": "email2@example.com"
},{
"_id": "5c87bda25fda8b00171001e1",
"name": "User Name",
"email": "email@example.com"
}
Run Code Online (Sandbox Code Playgroud)
我还有一个包含 _userId 键的对象数组。我需要获取用户 _id 等于数组中 _userId 值的所有用户。
[
{_userId: "5c87bda25fda8b00171001e1"},
{_userId: "5c87bda25fdaasdf00171001e1"},
]
Run Code Online (Sandbox Code Playgroud)
到目前为止我所拥有的是:
User.find(
{
_id: { $in: req.body.users }
}
)
Run Code Online (Sandbox Code Playgroud)
如果 req.body.users 只是一个 ids 数组,而不是对象数组,那应该没问题。
任何帮助将不胜感激。谢谢,
您应该像这样修改您的查询:
User.find({
_id: { $in: req.body.users.map(user => ObjectId(user._userId) }
});
Run Code Online (Sandbox Code Playgroud)
您需要将 _userId 字符串转换为 ObjectId。这将通过map功能来完成。
| 归档时间: |
|
| 查看次数: |
1574 次 |
| 最近记录: |