【问题标题】:Mongoose: updating new values only if not nullMongoose:仅当不为空时才更新新值
【发布时间】:2019-11-28 03:37:38
【问题描述】:

我已经有了另一个解决方案,但不明白为什么我的不起作用。

我尝试在这里使用 $set: 但没有帮助。当我打印时,objForUpdate 确实返回“姓名,姓氏”。如果我用 {name, lastname} 替换 {objForUpdate} - 更新有效。但我不能在变量中传递参数。

//Route to UPDATE user
    async updateUser(req, res) {
        let { _id, type, name, lastname } = req.body;
        try {
             let objForUpdate = "";
             for (var key in req.body) {
                 if (req.body.hasOwnProperty(key) && req.body.key !== null && req.body[key] !== "" && key !== '_id') {
                     console.log("this is key: " + key + ", and this is value req.body[key]: " + req.body[key]);
                     objForUpdate += key + ", ";
                 }
            }
            objForUpdate = objForUpdate.slice(0, -2); 
            const updated = await Users.updateOne({ _id }, {objForUpdate});
            res.send({ updated });
        } catch (error) {
            res.send({ error });
        }
    }

【问题讨论】:

    标签: javascript mongodb object mongoose


    【解决方案1】:

    如果你会调试代码,你会得到它。

    假设req.body 看起来像{ name: "foo", lastname: "bar" type: "2", _id: 1},在for 循环和切片操作结束时,objForUpdate 将是"name, lastname, type",这是一个字符串。 p>

    现在,当您将此字符串传递给 updateOne 操作时,这部分 {objForUpdate} 将被转换为 { objForUpdate: "name, lastname, type" }(标识符作为键的转换及其定义value 作为该键的值)。

    即使使用$set 运算符,更新对象也不正确。


    如果我用 {name, lastname} 替换 {objForUpdate} - 更新有效。为什么?

    因为在这种情况下使用Object destructuring,您将对象解压缩为带有值的独立变量(姓名、姓氏...)。在这种情况下,传递时的 {objForUpdate} 将变为 {"name":"foo", "lastname":"bar", "type":"2"},这是正确的更新对象。

    【讨论】:

      猜你喜欢
      • 2013-03-09
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 2017-09-16
      • 2015-01-02
      • 2017-02-27
      相关资源
      最近更新 更多