mongoose save vs insert vs create

前端 未结 1 1051
情书的邮戳
情书的邮戳 2020-12-12 16:30

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

My current attempt:

var mongoose = require(\'mongo         


        
相关标签:
1条回答
  • 2020-12-12 16:37

    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.

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

    0 讨论(0)
提交回复
热议问题