Javascript 猫鼬保存 vs 插入 vs 创建

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38290684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:16:57  来源:igfitidea点击:

mongoose save vs insert vs create

javascriptnode.jsmongodbmongoose

提问by Maria Jane

What are different ways to insert a document(record) into MongoDB using Mongoose?

使用 Mongoose 将文档(记录)插入到 MongoDB 中有哪些不同的方法?

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.

知道为什么插入和保存在我的情况下不起作用吗?我尝试创建,它插入了 2 个文档而不是 1 个。这很奇怪。

回答by Iceman

The .save()is an instance method of the model, while the .create()is called directly from the Modelas a method call, being static in nature, and takes the object as a first parameter.

.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!
    })
}

Export whatever functions you would want outside.

导出您想要的任何功能。

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

更多在Mongoose Docs,或者考虑阅读ModelMongoose 中原型的参考。