我使用mongoose,我有以下列表:
const ids: ["63bd7878f1f085f7d8a6827f", "63be730bf1f085f7d8a682c8"];
我想把ids
变成一个ObjectIds列表..
我试过以下方法:
const affectedUsers = await Users.find(
{ _id: { $in: [ids.map(e => mongoose.Types.ObjectId(e))] } }
);
但是它给了我以下错误:
"message": "Cast to ObjectId failed for value "[n new
ObjectId("63bd7878f1f085f7d8a6827f"),n new
ObjectId("63be730bf1f085f7d8a682c8")n]"
(type Array) at path "_id" for model "users""
您已经在$in
查询中添加了额外的括号,试试这个…
const affectedUsers = await Users.find(
{ _id: { $in: ids.map(e => mongoose.Types.ObjectId(e)) } }
);
您应该删除$in
操作符中的额外数组,如下所示:
const affectedUsers = await Users.find(
{ _id: { $in: ids.map(e => mongoose.Types.ObjectId(e)) } });