使用 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 个。这很奇怪。
最佳答案
.save()
是模型的实例方法,而 .create()
是直接从 Model
调用的方法调用,本质上是静态的,并将对象作为第一个参数。
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!
})
}
导出您想要的任何功能。
更多信息请访问 Mongoose Docs ,或考虑阅读 Model
的引用资料Mongoose 中的原型(prototype)。
关于javascript - Mongoose 保存与插入与创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38290684/