本文介绍了mongoose save vs insert vs create的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用Mongoose将文档(记录)插入MongoDB有哪些不同方法?
我当前的尝试:
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
}
任何想法为什么插入和保存不在我的情况下工作?我试过创建,它插入2个文件而不是1.这很奇怪。
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( )
是模型的实例方法,而 .create()
是直接从模型中调用的
作为方法调用,本质上是静态的,并将对象作为第一个参数。
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 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!
})
}
导出你想要的任何功能。
Export whatever functions you would want outside.
更多信息,请访问,或考虑阅读原型的参考在Mongoose。
More at the Mongoose Docs, or consider reading the reference of the Model
prototype in Mongoose.
这篇关于mongoose save vs insert vs create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!