'Mongoose-Unique-Validator giving unique error when trying to update a field (MongoDB/JavaScript)

I have a blog application using MongoDB/Mongoose on an Express server. I am using Mongoose-Unique-Validator.

Each user document has a posts field which is an array consisting of post ID's. When a user makes a new post, I attempt to update their document to add the post to their posts array:

let user = await User.findById("61b45baa09caf8ee462248df")
    await post.save().then(savedPost => {
        user.posts = user.posts.concat(savedPost.id)
        user.save()
    })

When this code is run, the following error is outputted:

  errors: {
    _id: ValidatorError: Error, expected `_id` to be unique. Value: `61b45baa09caf8ee462248df`
        at validate (C:\Users\avery\Desktop\blog\backend\node_modules\mongoose\lib\schematype.js:1277:13)
        at C:\Users\avery\Desktop\blog\backend\node_modules\mongoose\lib\schematype.js:1252:24
        at processTicksAndRejections (node:internal/process/task_queues:96:5) {
      properties: [Object],
      kind: 'unique',
      path: '_id',
      value: new ObjectId("61b45baa09caf8ee462248df"),
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'User validation failed'

My userSchema is as follows::

const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')

const userSchema = mongoose.Schema({
    username: {
        type: String,
        unique: true
    },
    passwordHash: String,
    posts: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref:'Post'
        }
    ]
})

userSchema.plugin(uniqueValidator)

userSchema.set('toJSON', {
    transform: (document, returnedObject) => {
        returnedObject.id = returnedObject._id.toString()
        delete returnedObject._id
        delete returnedObject.__v
        delete returnedObject.passwordHash
    }
})

const User = mongoose.model('User', userSchema)

module.exports = User

What the issue is here?



Solution 1:[1]

This issue is already mentioned on its github repository. this may help.Mentioned in official Github of Plugin

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1