Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

What are the different ways to insert a document(a record) into MongoDB using Mongoose?

My current attempt:

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var notificationsSchema = mongoose.Schema({

    "datetime" : {

        type: Date,

        default: Date.now

    },

    "ownerId":{

        type:String

    },

    "customerId" : {

        type:String

    },

    "title" : {

        type:String

    },

    "message" : {

        type:String

    }

});

var notifications = module.exports = mongoose.model('notifications', notificationsSchema);

module.exports.saveNotification = function(notificationObj, callback){

    //notifications.insert(notificationObj); won't work

    //notifications.save(notificationObj); won't work

    notifications.create(notificationObj); //work but created duplicated document

}

Any idea why insert and save doesn't work in my case? I tried to create, it inserted 2 documents instead of 1. That's strange.

1 Answer

0 votes
by (108k points)

The .save() is considered to be an instance method of the model, while the .create() is called straight from the Model as a method call, being static in nature, and takes the object as a first parameter.

Related questions

0 votes
1 answer
0 votes
1 answer

Browse Categories

...