猫鼬保存 vs 插入 vs 创建 [英] mongoose save vs insert vs create

查看:23
本文介绍了猫鼬保存 vs 插入 vs 创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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()作为方法调用直接从 Model 调用,本质上是静态的,并将对象作为第一个参数.

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 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 Docs 中了解更多信息,或考虑阅读 Model 猫鼬中的原型.

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

这篇关于猫鼬保存 vs 插入 vs 创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆