2016-07-10 23 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 बनाम बनाम बनाम बनाम

+1

यह आपकी मदद नहीं करता है जब आप एक ही समस्या को कई बार पोस्ट करते हैं http://stackoverflow.com/questions/38290506/mongoose-create-created-multiple-document ... – DAXaholic

+1

@DAXaholic क्या आपकी कोई समस्या है ? –

+0

@ मारियाजेन क्यूड आप 'अधिसूचना ओबीजे' के रूप में पारित वस्तु की घोषणा दिखाते हैं। – Iceman

उत्तर

25

.save() विधि मॉडल उदाहरण की एक संपत्ति है, जबकि .create() को मॉडल से सीधे संपत्ति के रूप में बुलाया जाता है और ऑब्जेक्ट को पहले पैरामीटर के रूप में ले जाता है।

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 दस्तावेज़ मिलता है, कोई विचार क्यों? –

संबंधित मुद्दे