【问题标题】:Mongoose updateOne() going through okay but not updatingMongoose updateOne() 正常但没有更新
【发布时间】:2021-12-08 00:51:02
【问题描述】:

我有这个要求:

// PUT that updates a user. 
router.put('/api/user/:id', async (req: Request, res: Response) => {
    const { email, name, avatar } = req.body

    const userId = req.body._id
    const conditions = {
        _id : userId
    }

    const user = {$set: { "email": email, "name": name, "avatar": avatar } }
    
    User.updateOne(conditions, user).then(doc => {
        if (!doc) { return res.status(404).end() }
        return res.status(200).json(doc)
    }).catch(error => console.log(error))
})

我从请求中得到了这个响应:

{
    "n": 0,
    "nModified": 0,
    "ok": 1
}

如果您可以在 StackOverflow 上找到有关 mongoose 中的 updateOne() 方法的信息,我可能已经尝试过了。无论我如何尝试,文档都不会更新。

编辑:我尝试在查询中使用 ObjectID,结果相同。

编辑 2:我想通了。正在使用 req.body.id 而不是 req.params.id 并且我正在使用参数来发送请求。感谢大家的帮助!

【问题讨论】:

  • 你确定你的病情有结果吗?
  • 似乎不是出于某种原因。
  • 欢迎来到stackoverflow。我建议您阅读如何提出一个好问题 (stackoverflow.com/help/how-to-ask)。
  • 您为用户 ID req.body._id 传递了错误的变量,它应该是 req.params.id

标签: javascript node.js mongodb mongoose


【解决方案1】:

nModified == 0 表示您没有匹配此 id 的用户,

您的路线是 put /api/user/:id您的用户 ID 在 req.params.id 而不是 req.body._id

【讨论】:

    【解决方案2】:

    几个提示:

    尝试在命令行从 mongodb 运行相同的查询,看看是否有任何结果。 “campaign_id”是否在您的架构中定义为 ObjectId?如果是这样,请尝试使用 ObjectId 类型进行搜索。

    尝试将查询更改为:

    const ObjectId = require('mongoose').Types.ObjectId; 
      const conditions = {
            _id : new ObjectId(userId)
        }
    

    不更新的原因是 - mongoose 无法使用您提供的 id 搜索。

    【讨论】:

    • 这样做并在请求中添加 upsert: true 对象使其工作,这意味着文档可能首先不存在?我想我也试过这个。无论如何,感谢您的帮助!
    • 实际上是 nvm,它只插入了一个名为 index 的字段和 _id 出于某种原因,回到第一格。编辑:当我对同一个用户运行 get 时,它会返回用户,所以我不确定。
    【解决方案3】:

    如果您想根据_id 更新文档,您可以使用findByIdAndUpdate()

    const userId = req.body._id;
    const user =  { "email": email, "name": name, "avatar": avatar } 
    User.findByIdAndUpdate(userId , user, 
        function (err, docs) { 
        if (err){ 
            console.log(err) 
        } 
        else{ 
            console.log("Updated User : ", docs); 
        } 
    }); 
    

    【讨论】:

    • 出于某种原因,这会将用户列为 null,即使我在完全相同的 id 上运行 get 请求,我也会得到结果。
    【解决方案4】:

    如果您已将数据库设置为严格模式,请不要忘记在添加新密钥时在选项中添加 strict:false。否则,插入将被静默忽略。我刚刚花了 2 个小时想知道为什么我的插入内容没有被保存在数据库中,尽管没有抛出任何错误。

    见dos http://mongoosejs.com/docs/guide.html#strict

    const conditions = {
        _id
    }
    
    const dateToUpdate =  {
        $set: {
            "email": "email",
            "name": "name",
            "avatar": "avatar"
        }
    }
    
    const updateRecord = await models.pdDealModel.updateOne(conditions,dateToUpdate,{
            upsert:false,
            strict:false
        }
        
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 2021-07-19
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      相关资源
      最近更新 更多