mongoose保存vs插入vs创build

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 } 

任何想法,为什么插入和保存不起作用在我的情况? 我尝试创build,它插入2文件,而不是1.这很奇怪。

       

网上收集的解决方案 "mongoose保存vs插入vs创build"

.save()方法是模型实例的一个属性,而.create()是作为属性直接从Model中调用的,并将该对象作为第一个参数。

 var mongoose = require('mongoose'); var Schema = mongoose.Schema; 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! }) } 

导出你想要的任何function。

更多在mongoose文件 。