【问题标题】:How do you delete a certain id from a document in mongoose? Edit: Why didn't this work (see edit)如何从 mongoose 的文档中删除某个 id?编辑:为什么这不起作用(见编辑)
【发布时间】:2020-05-14 12:50:51
【问题描述】:

所以我现在有这种类似的模式

user:{ _id: string,
       shifts:[_id:string],
       name: ... ,
       ...
}

现在我想从所有拥有这个的用户中删除一个 shift._id。

我已经有一个数组,其中包含他们的 id 具有此 shift._id 的所有用户。

我试过了,用 shift_id 作为我要删除的班次的 id:

userIdArray.forEach(user_id => {
    UserSchema.update({_id: user_id}, {$pull: {shifts: shift_id} });
  });

并得到错误:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:535:11)

谁能解释我做错了什么?

编辑:

所以我所做的是,我调用了一个名为:

function deleteShiftIdInUsers(users, shift_id){ 
users.forEach(user_id => {
    UserSchema.update({_id: user_id}, {$pull: {shifts: shift_id} });
  });}

并在我的 async (req, res, next) 路由中调用了这个函数。

现在我只是在异步函数中执行此代码,而不是像 code...; deleteShiftIdInUsers(users, shift_id); res.status(200).json(...); 那样执行此代码

还是 js 新手,我做错了什么?

【问题讨论】:

  • 你提到的错误不是 MongoDB 检查这个答案 - stackoverflow.com/questions/7042340/…
  • @PuneetSingh,你能帮我吗?因此,如果您阅读编辑,您会发现我的逻辑是……您知道在哪里或什么吗?
  • 你仍然在代码中循环调用你的查询不要这样做,使用更新很多,并使用 asun/await 等待

标签: mongodb express mongoose


【解决方案1】:

我认为,你需要用 async/await 调用 mongoose 函数,你应该使用 updateMany 和 $in 而不是循环 user_id

var ObjectId = require("mongoose").Types.ObjectId

async function deleteShiftIdInUsers(users, shift_id){ 
  users = users.map(user_id => ObjectId(user_id))
  return await UserSchema.updateMany({"_id": {"$in": users}}, {"$pull": {"shifts": ObjectId(shift_id)} });
}

当你调用这个函数时

await deleteShiftIdInUsers(users, shift_id);
res.status(200).json(...);

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    相关资源
    最近更新 更多