我正在嘗試做什麼。
我有一個userSchema
其中包含一個operationCountSchema
對象的列表。我試圖做的是創建一個靜態方法,如果它存在(由month_id
標識)字段,則更新count
字段中的某個操作計數子文檔。如果operationCountSchema
文檔在當月不存在,它應該創建一個新文檔。有沒有辦法在貓鼬中實現這種行爲?我曾嘗試使用upsert無濟於事。如何做到這一點?謝謝。貓鼬 - 在Subdoc上增加字段如果存在,否則創建新的
CODE
var operationCountSchema = mongoose.Schema({
month_id: String,
count: { type: Number, default: 0 }
}, {_id : false});
var userSchema = mongoose.Schema({
username : { type: String, unique: true, required: true },
email: { type: String, unique: true, required: true },
password: String,
operation_counts: [operationCountSchema]
});
userSchema.statics.incrementOperationCount = function(userID, callback) {
var currDate = new Date();
var dateIdentifier = currDate.getFullYear() + "-" + currDate.getMonth();
//NEED TO INCREMENT OPERATION COUNT IF ONE FOR MONTH EXISTS,
//ELSE IF IT DOES NOT EXIST, CREATE A NEW ONE.
}
而且,在此功能可以實現替代方式中的任何建議,歡迎。
通過靜態方法傳遞值並檢查子文檔是否存在(使用'this'關鍵字)。如果存在修改和調用回調。否則使用'this.sub-docment ='創建子文檔並調用回調。一旦調用回調函數,使用mongoose文件'save()'方法保存修改過的文檔。 –
'month_id'需要匹配以增加計數值是什麼? – Chinni
@Chinni month_id需要匹配dateIdentifier。 –