【问题标题】:mongoose save vs insert vs create猫鼬保存与插入与创建
【发布时间】:2016-11-12 10:34:56
【问题描述】:

使用 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 个。这很奇怪。

【问题讨论】:

  • 同一个问题多次发帖无济于事stackoverflow.com/questions/38290506/… ...
  • @DAXaholic 你对我的问题有任何线索吗?
  • @MariaJane cud u 显示以notificationObj 传递的对象声明。
  • 所以,create 和 save 方法属于 monggose 模型的对象。您需要创建并保存。我会发布一个答案。

标签: javascript node.js mongodb mongoose


【解决方案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,或考虑阅读 Mongoose 中 Model 原型的参考。

【讨论】:

  • 坦克从何而来?
  • @MariaJane 重新加载答案。我已经进行了编辑,我的意思是Notification。 Tank 来自等效文档。
  • 您的回答有帮助。这是我自己的错误。您很好地解释了保存和创建,但插入的最佳方法是什么?
  • 两者的行为相同。请记住,对于.save(),对象必须是模型的一个实例。因此,您必须格外小心,但从好的方面来说,您可以在函数之后将其传递给其他函数并保存在不需要模型变量的任何位置。它更像是一个自包含的实体。所以我更喜欢保存。
  • 当前 Mongoose API 中没有 insert 用于 document 或 model。有一个insertMany,它本质上是一个验证器和批量输入。没有在这里限定它,因为那是一个更“高级”的用例 :) 我猜。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 2014-07-15
  • 2021-09-25
  • 2019-02-09
  • 2018-08-27
相关资源
最近更新 更多