简体   繁体   English

如果我只有字符串形式的 ID,如何从数组中删除 objectId?

[英]How do I delete an objectId from an array if I only have the ID as a string?

I have an array of ObjectIDs in Client.users.我在 Client.users 中有一组 ObjectID。 I am trying to delete the ObjectId that matches the ID stored in the req.body.我正在尝试删除与 req.body 中存储的 ID 匹配的 ObjectId。 The ID stored is a string of "5fa0625514b0db02df53084b" - not in an ObjectID format.存储的 ID 是一串“5fa0625514b0db02df53084b”——不是 ObjectID 格式。

 const { id } = req.body; // this is 5fa0625514b0db02df53084b (second in the array) Client: { users: [ ObjectId("5fa027c614b0db02df530848"), ObjectId("5fa0625514b0db02df53084b") ] }

I have tried converting the string in the req.body to an object ID using Mongoose, but it still doesn't work.我尝试使用 Mongoose 将 req.body 中的字符串转换为对象 ID,但它仍然不起作用。

 let searchQuery = {"_id": jwt.id}; Client.findOneAndUpdate(searchQuery, { $pull: { "users": [mongoose.Types.ObjectId(id)] } })

Is it possible to remove an ObjectID from the array, if I only have it as a string to begin with?是否可以从数组中删除 ObjectID,如果我只将它作为字符串开头? I know there must be a way to convert it somehow, but the docs told me to use my attempt above, but it doesn't seem to work (doesn't remove the ObjectID from the array).我知道一定有办法以某种方式转换它,但是文档告诉我使用上面的尝试,但它似乎不起作用(不会从数组中删除 ObjectID)。

I'd be grateful if anyone could help.如果有人可以提供帮助,我将不胜感激。 Cheers干杯

There is a little error.有一个小错误。 When you pull you are using an array.当您pull您正在使用数组。

The correct query should be like this:正确的查询应该是这样的:

Client.updateOne(searchQuery,
{
  "$pull": {
    "users": mongoose.Types.ObjectId("5fa0625514b0db02df53084b")
  }
})

Also, the query should use mongoose.Types.ObjectId(jwt.id) to avoid problems.此外,查询应使用mongoose.Types.ObjectId(jwt.id)以避免出现问题。

Mongo playground example here Mongo 游乐场示例在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM