2016-07-10 5 views
15
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 
} 

私の場合、挿入と保存がうまくいかない理由は何ですか?私は作成しようとしましたが、1の代わりに2つのドキュメントを挿入しました。それは変です。mongoose save vs insert vs create

+1

同じ問題を何度も投稿すると助けにならないhttp://stackoverflow.com/questions/38290506/mongoose-create-created-multiple-document ... – DAXaholic

+1

@DAXaholicあなたは私の問題について何か手掛かりを持っていますか? ? –

+0

@MariaJane cud uは、 'notificationObj'として渡されたオブジェクトの宣言を表示します。 – Iceman

答えて

25

.create()は、プロパティとしてモデルから直接呼び出され、オブジェクトを最初のパラメータとして取り込みますが、.save()メソッドはモデルインスタンスのプロパティです。

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

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です。

+0

タンクはどこから来ますか? –

+0

@MariaJane答えをリロードしてください。私は編集を行いました、私は '通知'を意味しました。タンクは、同等のドキュメントからのものです。 – Iceman

+0

問題は、私が2つの文書をデータベースに挿入した、何らかの理由で作成したときです。 –