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.
.save() is a model instance method, while .create() is called directly from the Model as a method call, being static in nature, and takes the object as its 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 the features you want out.
More at Mongoose Docs , or consider reading the Mongoose Model prototype reference.
You can use save() or create() .
save() can only be used on a new model document, while create() can be used on the model. Below I have given a simple example.
const mongoose = require("mongoose"); const tourSchema = new mongoose.Schema({ name: { type: String, required: [true, "A tour must have a name"], unique: true, }, rating: { type: Number, default:3.0, }, price: { type: Number, required: [true, "A tour must have a price"], }, }); const Tour = mongoose.model("Tour", tourSchema); module.exports = Tour; const Tour = require('../models/tourModel'); exports.createTour = async (req, res) => { // method 1 const newTour = await Tour.create(req.body); // method 2 const newTour = new Tour(req.body); await newTour.save(); }Make sure to use Method 1 or Method 2.