XTP3
XTP3

Reputation: 1

Increment ($inc) update not working with upsert (MongoDB, NodeJS)

I am currently working on a MongoDB Post-Hashtag system, I am using NodeJS and the library "Mongoose". Following the creation of a new "post", I wish to increment the quantity of the "posts" field of the given hashtag's document, else if it does not exist: create a new document for the hashtag. I attempted to do this by utilizing the upsert option and performing a single update (updateOne) for each hashtag. The upserting & new document creation process for a new hashtag appears to work fine, however, pre-existing hashtags do not have their "posts" field incremented.

My code:

await Hashtag.updateOne({hashtag: hashtag}, {
  $set: {$inc: {posts: 1}},
  $setOnInsert: {
   uniqueID: hashtagID,
   hashtag: hashtag,
   timeOfCreation: now,
   posts: 1
 }
}, {upsert: true});

I have attempted both with & without the '$set' operator, as well as '$update' and '$inc' to no avail. Omitting it results in the following error:

{
    "errorType": "MongoServerError",
    "errorMessage": "Updating the path 'posts' would create a conflict at 'posts'",
    "code": 40,
    "index": 0,
    "stack": [
        "MongoServerError: Updating the path 'posts' would create a conflict at 'posts'",
    ...
}

My schema as defined in Mongoose:

const hashtagSchema = new mongoose.Schema({
    uniqueID: {
        type: String,
        required: true
    },
    hashtag: {
        type: String,
        required: true
    },
    timeOfCreation: {
        type: Number,
        required: true
    },
    posts: {
        type: Number,
        required: true
    },
});

Upvotes: 0

Views: 241

Answers (1)

Rohan Tripathi
Rohan Tripathi

Reputation: 1

Remove the $set which is used before $inc.

await Hashtag.updateOne({hashtag: hashtag}, {
      $inc: {posts: 1},
      $setOnInsert: {
       uniqueID: hashtagID,
       hashtag: hashtag,
       timeOfCreation: now,
       posts: 1enter code here
     }
    }, {upsert: true});

Upvotes: 0

Related Questions