I have a userSchema that contains a list of operationCountSchemaobjects. What I am trying to do, is to create a static method that updates the count field on one of these operation count subdocuments if it exists (identified by a month_id) field. If an operationCountSchema document does not exist for the current month, it should create a new document. Is there a way to achieve this behaviour in mongoose? I have tried using upsert to no avail. How would one do this? Thanks.
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.
}
Also, any suggestions on alternative ways in which this functionality can be achieved are welcome.
I think you want findOneAndUpdate() with upsert : true:
operationCountSchema.findOneAndUpdate({
month_id : dateIdentifier,
}, {
$inc : { count : 1 }
}, {
upsert : true
}, callback);
(untested)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With