Bardia
Bardia

Reputation: 155

set model values from json in nodejs

Hi Guys I want to know how to save json string into mongoose model object? let me explain a simplified version of my problem:

I have a schema model:

const mongo = require('mongoose');
const clientSchema = mongo.Schema({
    name: {type: String},
    age: {type: Number},
    updated_at: {type: Date},
}

and I have a put method which is shown below:

var Client = mongo.model('client', clientSchema);

//Update User
server.put(`/api/clients/:_id`, (req, res) =>
{
    Client.model.findById(req.params._id, (err, foundedclient) => 
    {
        if(err) res.send(err);

        //***********************************************************//
        /*I want to update foundedclient from req.body here!         */
        /*some function like : foundedclient.JsonTovalues(req.body); */  
        //***********************************************************//

        foundedclient.updated_at = new Date().toISOString();

        foundedclient.save((err) =>
        {
            res.send('saved successfully!');
        });
      });
});

the req.body is a json:

{
    "name":"bardia",
    "age":27,
}

I want to update foundedclient value from req.body at the position I highlighted in the code by //*******// signs. I want a hypothetical function such as foundedclient.JsonTovalues(req.body). what is the best way to achieve that? In other words what is the best way to save json as mode values?

Thank a lot

Upvotes: 1

Views: 979

Answers (1)

Nilesh Soni
Nilesh Soni

Reputation: 425

you can define an instance method to something similar to updateByJson as explained below

const clientSchema = mongo.Schema({
   name: {type: String},
   age: {type: Number},
   updated_at: {type: Date},
}

// here simply calling update method internally but exposed as an instance method 
clientSchema.methods.updateByJson = function(jsonToUpdate, cb){
   // will work if you are using mongoose old version 3.x
   this.constructor.update({_id: this._id}, {$set:jsonToUpdate}, cb);
   // should work with latest versions
   this.model('client').update({_id: this._id}, {$set:jsonToUpdate}, cb);
}

Your client code will look like this

var Client = mongo.model('client', clientSchema);

//Update User
server.put(`/api/clients/:_id`, (req, res) =>
{
    Client.model.findById(req.params._id, (err, foundedclient) => 
    {
        if(err) res.send(err);

        jsonToUpdate = req.body
        jsonToUpdate.updated_at = new Date().toISOString();

        foundedclient.updateByJson(jsonToUpdate, (err) => {
            res.send('saved successfully!');
        });
      });
});

I hope this helps you.

Upvotes: 5

Related Questions