【问题标题】:Mongodb/Mongoose: one field will not updated by empty stringMongodb/Mongoose:一个字段不会被空字符串更新
【发布时间】:2017-02-12 15:18:29
【问题描述】:

我是 MongoDB/Mongoose 的新手,遇到以下问题:

我的架构嵌套在:

profile: {
school: {type: String, required: false},
subject: {type: String, required: false}, 
graduation: {type: String, required: false}
}

现在我想更新学校、学科和毕业情况:

userRouter.put('/:id', function(req, res, next){

  var updateObject = req.body;

 User.findByIdAndUpdate(req.params['id'], updateObject,{upsert: true}, (err, success)=> {
if(err)
  res.status(404).send(err);
     res.status(200).send();
  });
});

我知道 put 方法替换了对象,但是 patch 方法没有在我的代码中运行。现在,当我发送:

{"school": "", "subject": "c", "graduation": ""}

学科和毕业将被覆盖,但学校不会是空的 - 它包含旧的东西。

你有解决办法吗?谢谢。

【问题讨论】:

    标签: node.js mongodb typescript mongoose


    【解决方案1】:

    测试像这所学校和毕业被修改...

        let updateObject = {
            profile: {school: "", subject: "c", graduation: ""}
        };
    
        user.findByIdAndUpdate(
            req.params['id'],
            updateObject,
            {upsert: true},
            function(err, success) {
                if (err)
                    res.status(404).send(err);
                res.status(200).send();
            }
        );
    

    使用了这个测试架构:

    new mongoose.Schema({
        created: {type: Date, required: true, default: Date.now},
        modified: {type: Date, required: true, default: Date.now},
        profile: {
            school: {type: String, required: false},
            subject: {type: String, required: false},
            graduation: {type: String, required: false}
        }
    
    },
    {
        collection: 'db_test',
        strict: 'throw',
        toJSON: {getters: true},
        toObject: {getters: true}
    }
    );
    

    【讨论】:

      猜你喜欢
      • 2021-06-21
      • 2015-10-01
      • 1970-01-01
      • 2019-09-27
      • 2015-10-05
      • 2022-12-06
      • 2015-03-25
      • 2020-10-01
      • 1970-01-01
      相关资源
      最近更新 更多