javascript - Mongoose 保存与插入与创建

标签 javascript node.js mongodb mongoose

使用 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/

相关文章:

javascript - 无法在 React 应用程序中禁用指针事件

javascript - protobuf.js : print int64 Object as string in node. js

javascript - 从 php 文件运行命令行程序

javascript - MySQL 查询未按顺序执行 (NodeJS)

mongodb - 在 MongoDB 中对子文档进行排序

javascript - NodeJS客户端中MongoDB中的BulkWriteError

javascript - 如何让这个 slider 以一定的延迟自动循环? IE。 1000毫秒

asp.net - __doPostback - 从 JavaScript 调用事件背后的代码?

node.js - Sequelize 包括创建一个嵌套对象

mongodb - 如何检查 mongo db 是否在 Mac 上运行?