Example update document in mongodb with nodejs use mongoose

Update Document

You can update a record, or document as it is called in MongoDB, by using the findOneAndUpdate () method.

The first parameter of the findOneAndUpdate () method is a query object defining which document to update.

Note: If the query finds more than one record, only the first occurrence is updated.

The second parameter is an object defining the new values of the document.

Example: Update the document with the address "Valley 345" to name="name15" and address="Canyon 123"

 

var mongoose = require('mongoose');

mongoose.connect('mongodb://192.168.1.122:27017/codewr');

var db = mongoose.connection;

var Schema = mongoose.Schema;

var customers = new Schema({

    name: {type: String, required: true},

    address: {type: String, required: true}

});

 

var customerObject = db.model('customers', customers);

customerObject.findOneAndUpdate({name: "name1"}

, {$set: {address: "Highway"}}

, function (err, doc) {

    if (err) {

        console.log("update document error");

    } else {

        console.log("update document success");

        console.log(doc);

    }

});

 

Run and result:

 

C:\Nodejs>node mongooseUpdateOneDocument.js

update document success

{ _id: 5adf11285075b4199c20efb8,

  name: 'name1',

  address: 'Highway 71',

  __v: 0 }

 

Update Many Documents

To update all documents that meets the criteria of the query, use the updateMany() method.

Example: Update all documents where the name is “name1”

 

var MongoClient = require('mongodb').MongoClient;

var mongoose = require('mongoose');

mongoose.connect('mongodb://192.168.1.43:27017/codewr');

var db = mongoose.connection;

var Schema = mongoose.Schema;

var customers = new Schema({

    name: {type: String, required: true},

    address: {type: String, required: true}

});

var customerObject = db.model('customers', customers);

var query= {name: "name1"};

var valueUpdate = {$set: {address: "Highway1"}};

customerObject.updateMany(query

, valueUpdate

, function (err, result) {

    if (err) {

        console.log("update document error");

    } else {

        console.log("update document success");

        console.log(result);

    }

});

 

Run and result:

 

C:\Nodejs>node mongooseUpdateManyDocument.js

update document success

{ n: 3, nModified: 3, ok: 1 }