Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

$inc on non-existing field results in NaN #12435

Closed
2 tasks done
Hybrid-Force opened this issue Sep 16, 2022 · 0 comments · Fixed by #12437
Closed
2 tasks done

$inc on non-existing field results in NaN #12435

Hybrid-Force opened this issue Sep 16, 2022 · 0 comments · Fixed by #12437

Comments

@Hybrid-Force
Copy link

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

6.6.1

Node.js version

16.15.0

MongoDB server version

4.2.1

Description

According to MongoDB document on $inc,

If the field does not exist, $inc creates the field and sets the field to the specified value.

In Mongoose, $inc operations on non-existing fields result in correct data in the database, however, the field in Mongoose document will become NaN because currentValue is undefined.

mongoose/lib/document.js

Lines 1738 to 1740 in 586c86f

const currentValue = this.$__getValue(path);
this.$__setValue(path, currentValue + val);

Steps to Reproduce

import mongoose from 'mongoose';
const schema = new mongoose.Schema({
    count: Number,
    // no default value, not required
});
const Model = mongoose.model('IncTest', schema);
await Model.collection.drop();
const doc = new Model({
    // optional 'count' field no set
});
await doc.save();
doc.$inc('count', 1);
await doc.save();

// doc.count is expected to be 1.
// But instead, it is NaN

Expected Behavior

No response

@Hybrid-Force Hybrid-Force changed the title $inc on non-existing field resulting in NaN $inc on non-existing field results in NaN Sep 16, 2022
lpizzinidev added a commit to lpizzinidev/mongoose that referenced this issue Sep 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant