Home > Back-end >  MongoDB Atlas and Mongoose, unique "_id" not registering as unique
MongoDB Atlas and Mongoose, unique "_id" not registering as unique

Time:10-21

I am trying to create a new instance of a place for a specific user. When I look at my MongoDB Atlas the "_id" 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) => {
  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: `616d8a452c5215f9fafb6052`
    at ValidationError.inspect (/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("616d8a452c5215f9fafb6052"),
      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.

CodePudding user response:

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

  • Related