javascript - 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/

相关文章:

mongodb - 如何在 mongodb 配置文件中设置授权?

mongodb - 在 MongoDB 中执行搜索/投影时如何重命名字段?

mongodb - 聚合框架中的 $skip 和 $limit

node.js - Mongoose - 验证电子邮件语法

mongodb - 如何在 MongoDB shell 中中止正在运行的查询?

mongodb - 在 Meteor 中运行示例的问题

node.js - Nodejs 中的 Mongodb 与 Postgres

mongodb - 升级mongodb没有效果仍然显示旧版本

shell - 为 MongoDB shell 设置默认数据库

node.js - MongoDB - 错误 : invalid schema, 预期 mongod