如果在更新时属性的值为null,则不应将该属性添加到记录中 [英] If value of a property is null when updating then that property should not be added to the record

查看:283
本文介绍了如果在更新时属性的值为null,则不应将该属性添加到记录中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的猫鼬模式:

Suppose I have a mongoose schema like this:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var testSchema = new Schema({
    name: {type: String, required: true},
    nickName: {type: String}
});

var Test = module.exports = mongoose.model('Test', testSchema);

我使用变量Test声明了CRUD操作的方法。从那一个这样的方法是更新,其定义如下:

I declare methods for CRUD operation using variable Test. From that one such method is update, which is defined as follows:

module.exports.updateTest = function(updatedValues, callback) {

    console.log(updatedValues); //this output is shown below

    Test.update(
        { "_id": updatedValues.id },
        { "$set" : { "name" : updatedValues.name, "nickName" : updatedValues.nickName } },
        { multi: false },
        callback
    );

};

现在,我在节点路由器中使用此方法,如下所示:

Now, I use this method inside my node router as follows:

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

    var id = req.params.id,
    var name = req.body.name,
    var nickName = req.body.nickName

    req.checkBody("name", "Name is required").notEmpty();

    var errors = req.validationErrors();

    if(errors) { ........ }
    else {

        var testToUpdate = new Test({
            _id: id,
            name: name,
            nickName: nickName || undefined
        });

        Test.updateTest(testToUpdate, function(err, result) {
            if(err) { throw(err); }
            else { res.status(200).json({"success": "Test updated successfully"}); }
        });

    }
});

现在如果我在数据库中保存新记录然后在数据库中看到它,那么它看起来像: / p>

Now if I save a new record in database and then see it in database then it looks like:

{
    "_id" : ObjectId("ns8f9yyuo32hru0fu23oh"), //some automatically generated id 
    "name" : "firstTest",
    "__v" : 0
}

现在,如果我在不更改任何内容的情况下更新同一文档,然后如果我查看数据库中的相同记录,那么我得到:

Now if I update the same document without changing anything and then if I take a look at same record in database, then I get:

{
    "_id" : ObjectId("ns8f9yyuo32hru0fu23oh"), //some automatically generated id 
    "name" : "firstTest",
    "__v" : 0,
    "nickName" : null
}

你能看到nickName设置为null吗?我不希望它像这样工作。我希望如果我的属性为null,那么该属性不应该包含在记录中。

Can you see that nickName is set to null? I don't want it to work like this. I want that if my property is null, then that property should not be included in the record.

如果你还记得,我有控制台在更新之前记录了updatedValues。 (参见第二个代码块)。所以,这是记录的值:

If you remember, I have console logged the updatedValues before updating it. (see the second code block in question). So, here is the logged values:

{
    "_id" : ObjectId("ns8f9yyuo32hru0fu23oh"), //some automatically generated id 
    "name" : "firstTest"
}

I不知道为什么,但是nickName不存在于记录的值中,然后在更新后我得到 nickName:null 。我认为,问题在于第二个代码块。你能检查吗?

I don't know why, but nickName is not present in the logged values and then after update I get nickName: null. I think, the problem lies in second Code block. Can you please check it?

注意:

其实我还有很多我的架构中的字段比我指定的字段。有些字段也是对其他记录的引用。

Actually I have lot more fields in my schema than I specified in question. Some fields are reference to other records as well.

推荐答案

我不会这样写,但我会告诉你的为什么你的代码失败。

I wouldn't write this this way, but I'll tell you why your code is failing.

问题是你的$ set block

The problem is your $set block

你选择专门设置传入更新对象的值。如果值为 undefined ,则强制mongo将其设置为null。

you're choosing to specifically set the value to the update object passed in. If the value is undefined you're forcing mongo to set that to null.

这是问题

例如,在DB中:

{
_id:ObjectId(ns8f9yyuo32hru0fu23oh),
name:firstTest,
nickname:jack,
__v:0
}

如果您传入 testToUpdate = {name:'foo'} 你最终会得到
Test.update({...},{$ set:{name:'foo',昵称:undefined}}

IF you pass in testToUpdate = { name: 'foo' } you'll end up with Test.update({ ... }, { $set: { name: 'foo', nickname: undefined }}

因为你得到了 updatedValues.nickname off of the arguments and thats not defined

because you're getting updatedValues.nickname off of the arguments and thats not defined

什么你想要的是
Test.update({...},{$ set:updatedValues} ,它转换为 Test.update( {...},{$ set:{name:'foo'}}

what you WANT is Test.update({ ... }, { $set: updatedValues } which is translates to Test.update({ ... }, { $set: { name: 'foo' } }.

您不再提供密钥昵称,因此不会将其设置为undefined / null。

You're no longer providing a key for nickname, thus not making it set to undefined/null.

我会使用mongoose插件而不用担心手动传递字段一直到你的模型

I would use a mongoose plugin and not worry about manually passing the fields all the way to your model

参见 https://github.com/autolotto/mongoose-model-update

您可以定义可更新字段,然后就可以了

you can define the update-able fields and then you can just do

model.update(req.body)而不用担心这一切

即使您不想使用该插件,您仍然可以这样做

Even if you don't want to use the plugin you can still just do

Test.findByIdAndUpdate(id, {name,nickname},callback)

这篇关于如果在更新时属性的值为null,则不应将该属性添加到记录中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆