Title: MongoDB Atlas and Mongoose, unique "_id" not registering as unique
Tags: javascript;node.js;express;mongoose;mongodb-atlas
Question: I am trying to create a new instance of a place for a specific user. When I look at my MongoDB Atlas the &quot;_id&quot; values for each user are in fact unique. When I have one user instance in the database I can create as many places as I want for that user. The problem arises when I create a new user, I can no longer create any new places for either user.
Here is the error I get on the frontend:
places-controllers.js
const { validationResult } = require('express-validator');
const mongoose = require('mongoose');
const getCoordsFromAddress = require('../util/location');
const HttpError = require('../models/http-error');
const Place = require('../models/place');
const User = require('../models/user');
const createPlace = async (req, res, next) =&gt; {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(
new HttpError('Invalid inputs passed, please check your data.', 422)
);
const { title, description, address, creator } = req.body;
let coordinates;
try {
coordinates = await getCoordsFromAddress(address);
} catch (error) {
return next(error);
const createdPlace = new Place({
title,
description,
address,
location: coordinates,
image: req.file.path,
creator,
let user;
try {
user = await User.findById(creator);
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again.',
500
);
return next(error);
if (!user) {
const error = new HttpError('Could not find user for provided id.', 404);
return next(error);
console.log(user);
//THIS SEEMS TO BE THE POINT WHERE THE CODE FAILS
try {
const session = await mongoose.startSession();
session.startTransaction();
await createdPlace.save({ session: session });
user.places.push(createdPlace);
await user.save({ session: session });
await session.commitTransaction();
} catch (err) {
console.log(err);
const error = new HttpError(
'Creating place failed, please try again.',
500
);
return next(error);
res.status(201).json({ place: createdPlace });
Then here is the schema:
place.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const placeSchema = new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
image: { type: String, required: true }, //url for a database
address: { type: String, required: true },
location: {
lat: { type: Number, required: true },
lng: { type: Number, required: true },
creator: { type: mongoose.Types.ObjectId, required: true, ref: 'User' },
module.exports = mongoose.model('Place', placeSchema);
and finally the error code:
Error: User validation failed: _id: Error, expected `_id` to be unique. Value: `zsullivan@example.org (/Users/james/Desktop/Full Stack Udemy Course (MERN)/Fullstack-app/server/node_modules/mongoose/lib/error/validation.js:48:26)
at internal/per_context/primordials.js:23:32
at formatValue (internal/util/inspect.js:774:19)
at inspect (internal/util/inspect.js:336:10)
at formatWithOptionsInternal (internal/util/inspect.js:2006:40)
at formatWithOptions (internal/util/inspect.js:1888:10)
at console.value (internal/console/constructor.js:313:14)
at console.log (internal/console/constructor.js:348:61)
at createPlace (/Users/james/Desktop/Full Stack Udemy Course (MERN)/Fullstack-app/server/controllers/places-controllers.js:112:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
errors: {
_id: ValidatorError: Error, expected `_id` to be unique. Value: `616d8a452c5215f9fafb6052`
at validate (/Users/james/Desktop/Full Stack Udemy Course (MERN)/Fullstack-app/server/node_modules/mongoose/lib/schematype.js:1277:13)
at /Users/james/Desktop/Full Stack Udemy Course (MERN)/Fullstack-app/server/node_modules/mongoose/lib/schematype.js:1252:24
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
properties: [Object],
kind: 'unique',
path: '_id',
value: new ObjectId(&quot;616d8a452c5215f9fafb6052&quot;),
reason: undefined,
[Symbol(mongoose:validatorError)]: true
_message: 'User validation failed'
Any help would be greatly appreciated, I have been scratching my head over this for a while now.
Comment: @JeremyThille Sadly, no, that isn't working. Is there anything else I should add to the post that would help? This is my first time asking other people for help, I'm not 100% sure what is needed.

Comment: @JeremyThille Thanks very much, re-rolling mongoose and mongoose-unique-validator seems to work. :)

Comment: I guess your error comes from line  `user = await User.findById(creator);` because its unable to get the creator value from req.body

Comment: Blind guess, after `user.places.push(createdPlace)` try adding `user.markModified("places");` ?

Comment: I found [this](https://github.com/blakehaswell/mongoose-unique-validator/issues/88), apparently it's some bug introduced in `mongoose-unique-validator` v2.0.2...

Here is the accepted answer: Answered
Courtesy of @JeremyThille.
mongoose-unique-validator has a bug in it so that when you have multiple users it detects the reference to _id in another schema. Then it decides that _id is no longer unique and will not let any user post a new Document.
The fix at the moment is to re-roll mongoose and mongoose-unique-validator to v^5.11.13 and v^2.0.3 respectively.
There is a current GitHub issue posted here.
https://github.com/blakehaswell/mongoose-unique-validator/issues/131


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 5, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:10/18/21', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<javascript><node.js><express><mongoose><mongodb-atlas>', 'Title': 'MongoDB Atlas and Mongoose, unique "_id" not registering as unique', 'ViewCount': 163, 'id': 69618716, 'user_AboutMe': None, 'user_AccountId': 20589402.0, 'user_DisplayName': 'James Beswick', 'user_Reputation': 41.0, 'user_Views': 1.0, 'user_id': 15113477.0}}