Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
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?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!