What are different ways to insert a document(record) into MongoDB using Mongoose?
My current attempt:
JavaScript
x
30
30
1
var mongoose = require('mongoose');
2
var Schema = mongoose.Schema;
3
4
var notificationsSchema = mongoose.Schema({
5
"datetime" : {
6
type: Date,
7
default: Date.now
8
},
9
"ownerId":{
10
type:String
11
},
12
"customerId" : {
13
type:String
14
},
15
"title" : {
16
type:String
17
},
18
"message" : {
19
type:String
20
}
21
});
22
23
var notifications = module.exports = mongoose.model('notifications', notificationsSchema);
24
25
module.exports.saveNotification = function(notificationObj, callback){
26
//notifications.insert(notificationObj); won't work
27
//notifications.save(notificationObj); won't work
28
notifications.create(notificationObj); //work but created duplicated document
29
}
30
Any idea why insert and save doesn’t work in my case? I tried create, it inserted 2 document instead of 1. That’s strange.
Advertisement
Answer
The .save()
is an instance method of the model, while the .create()
is called directly from the Model
as a method call, being static in nature, and takes the object as a first parameter.
JavaScript
1
39
39
1
var mongoose = require('mongoose');
2
3
var notificationSchema = mongoose.Schema({
4
"datetime" : {
5
type: Date,
6
default: Date.now
7
},
8
"ownerId":{
9
type:String
10
},
11
"customerId" : {
12
type:String
13
},
14
"title" : {
15
type:String
16
},
17
"message" : {
18
type:String
19
}
20
});
21
22
var Notification = mongoose.model('Notification', notificationsSchema);
23
24
25
function saveNotification1(data) {
26
var notification = new Notification(data);
27
notification.save(function (err) {
28
if (err) return handleError(err);
29
// saved!
30
})
31
}
32
33
function saveNotification2(data) {
34
Notification.create(data, function (err, small) {
35
if (err) return handleError(err);
36
// saved!
37
})
38
}
39
Export whatever functions you would want outside.
More at the Mongoose Docs, or consider reading the reference of the Model
prototype in Mongoose.