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.findByIdAndUpdate("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:UsersaveryDesktopblogbackendnode_modulesmongooselibschematype.js:1277:13)
at C:UsersaveryDesktopblogbackendnode_modulesmongooselibschematype.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 User Schema 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
Can anyone please help me figure out what the issue is here? Thanks in advance <3