Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If value of a property is null when updating then that property should not be added to the record

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);

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"}); }
        });

    }
});

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
}

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.

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 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?

Note:

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

like image 233
Vishal Avatar asked Mar 14 '17 10:03

Vishal


People also ask

What does properties of null mean?

If a property's definition does not set the default value of a property, its default value is null.

What is ODM explain the features of mongoose?

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. MongoDB is a schema-less NoSQL document database.


1 Answers

You can prevent such documents from updating in MongoDB by setting the runValidators option to true in the update method.

Ex:

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

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

In addition, you can also set the option omitUndefined to true to prevent undefined values from being reflected.

Ex:

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

    Test.update(
      { "_id": updatedValues.id },
      { "$set" : { 
        "name" : updatedValues.name, "nickName" : updatedValues.nickName } ,
      },
      { multi: false, runValidators: true, omitUndefined: true },
      callback
    );
  };
like image 196
Jatin Parate Avatar answered Oct 28 '22 23:10

Jatin Parate