mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

CastError: Cast to [undefined] failed for value "["user"]" at path "roles"

Open AdamBCo opened this issue 7 years ago • 5 comments

I am currently receiving the following error when running a Mongoose query in a test environment utilizing supertest and jest.

CastError: Cast to [undefined] failed for value "["user"]" at path "roles"

I am using Mongoose 5.6.9 with the code below:

The Query

const _id = req.params._id

User.findOne({
	_id,
	roles: 'admin'
})
	.exec()
	.then(user => {
		if (!user) {
			return next(boom.badRequest("No User"))
		}
		res.status(200).json(user)
	})
	.catch(err => next(boom.badRequest(err)))

The User Model

const mongoose = require('mongoose')

const Roles = ['user', 'admin', 'gallery', 'artist', 'appraiser', 'beta', 'super', 'contractor', 'auction_house']

const schema = mongoose.Schema(
    {
		name: {
			type: String,
			trim: true
		},
		roles: {
	        type: [{
	            type: String,
	            enum: Roles
	        }],
	        default: ['user']
	    }

    },
	{
		timestamps: {
			createdAt: 'created_at',
			updatedAt: 'updated_at'
		}
	}
)

module.exports = mongoose.model('User', schema)

Can someone please help me figure out what's going on?

Thank you

AdamBCo avatar Aug 10 '19 00:08 AdamBCo

Maybe this is related to #8053

esetnik avatar Aug 10 '19 02:08 esetnik

@esetnik Thanks for pointing me to that issue. Unfortunately it showcases the creation of a User object; whereas I am simply trying to find one. I'm not sure where the case issue is occurring.

AdamBCo avatar Aug 10 '19 15:08 AdamBCo

The below script executes without error for me on 5.6.9, please modify the below script to demonstrate your issue.

const assert = require('assert');
const mongoose = require('mongoose');
mongoose.set('debug', true);

const GITHUB_ISSUE = `gh8058`;
const connectionString = `mongodb://localhost:27017/${ GITHUB_ISSUE }`;
const { Schema } = mongoose;

run().then(() => console.log('done')).catch(error => console.error(error.stack));

async function run() {
  await mongoose.connect(connectionString, { useNewUrlParser: true });
  await mongoose.connection.dropDatabase();
  
  const schema = mongoose.Schema(
    { 
      name: { 
        type: String,
        trim: true
      },
      roles: {
        type: [{
          type: String,
          enum: ['admin', 'super-admin']
        }],
        default: ['user']
      }
    });

  const User = mongoose.model('User', schema);

  await User.create({ name: 'test', roles: ['admin'] });
  const doc = await User.findOne({ roles: 'admin' });
  console.log(doc);
}

vkarpov15 avatar Aug 11 '19 15:08 vkarpov15

This looks to be a duplicate of #8053. It's a bug in Jest that we'll work around.

I strongly recommend moving off of Jest. Jest is an anti-pattern because it does so much monkeypatching that it creates a distinct JavaScript environment that isn't quite Node.js or a browser. Code that works in Jest may not work in Node.js and vice versa.

vkarpov15 avatar Aug 18 '19 00:08 vkarpov15

I had the same problem - I updated to 5.6.11 and it fixes it.

realeibo avatar Aug 29 '19 09:08 realeibo