Example delete document in mongodb with nodejs use mongoose

Delete Document

To delete a record, or document as it is called in MongoDB, we use the deleteOne() method.

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

Note: If the query finds more than one document, only the first occurrence is deleted

Example: Delete the document with the address "Mountain 21"

 

var mongoose = require('mongoose');

 

var db = mongoose.connection;

var Schema = mongoose.Schema;

db.on('error', console.error);

db.once('open', function () {

    console.log("db connect");

    var customers = new Schema({

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

        address: {type: String, required: true}

    });

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

    var query = { name: 'name1' };

    customerObject.deleteOne(query, function (err, result) {

        if (err) {

            console.log("error query");

        } else {

            console.log(result);

        }

    });

});

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

 

Run and result:

 

C:\Nodejs>node mongooseDeleteOneDocument.js

db connect

{ n: 1, ok: 1 }

 

Delete Many

To delete more than one document, use the deleteMany() method.

The first parameter of the deleteMany() method is a query object defining which documents to delete.

Example: Delete all documents were the name is “name1”

 

var mongoose = require('mongoose');

var db = mongoose.connection;

var Schema = mongoose.Schema;

db.on('error', console.error);

db.once('open', function () {

    console.log("db connect");

    var customers = new Schema({

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

        address: {type: String, required: true}

    });

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

    var query = { name: 'name1' };

    customerObject.deleteMany(query, function (err, result) {

        if (err) {

            console.log("error query");

        } else {

            console.log(result);

        }

    });

});

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

 

Run and result:

 

C:\Nodejs>node mongooseDeleteManyDocument.js

db connect

{ n: 2, ok: 1 }