Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  95] [ 2]  / answers: 1 / hits: 103019  / 8 Years ago, sun, july 10, 2016, 12:00:00

What are different ways to insert a document(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 create, it inserted 2 document instead of 1. That's strange.


More From » node.js

 Answers
9

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.



var mongoose = require('mongoose');

var notificationSchema = mongoose.Schema({
datetime : {
type: Date,
default: Date.now
},
ownerId:{
type:String
},
customerId : {
type:String
},
title : {
type:String
},
message : {
type:String
}
});

var Notification = mongoose.model('Notification', notificationsSchema);


function saveNotification1(data) {
var notification = new Notification(data);
notification.save(function (err) {
if (err) return handleError(err);
// saved!
})
}

function saveNotification2(data) {
Notification.create(data, function (err, small) {
if (err) return handleError(err);
// saved!
})
}


Export whatever functions you would want outside.



More at the Mongoose Docs, or consider reading the reference of the Model prototype in Mongoose.


[#61441] Thursday, July 7, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devane

Total Points: 451
Total Questions: 88
Total Answers: 100

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
;