Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - Increment Field On Subdoc if exists, else create new

What I am trying to do.

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.

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.
}

Also, any suggestions on alternative ways in which this functionality can be achieved are welcome.

like image 885
Anthony Dito Avatar asked Oct 26 '25 14:10

Anthony Dito


1 Answers

I think you want findOneAndUpdate() with upsert : true:

operationCountSchema.findOneAndUpdate({
  month_id : dateIdentifier,
}, { 
  $inc : { count : 1 }
}, {
  upsert : true
}, callback);

(untested)

like image 139
robertklep Avatar answered Oct 29 '25 02:10

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!