Search code examples
mongodbmongoose-schemamongoose-populate

Why do I get a casting error for the following mongooseJS schema?


I get the following error when attempting to test the schema:

"CastError: Cast to ObjectId failed for value "{ by: 58803a77479f7e2a2d069d93, at: 2017-01-19T04:03:03.156Z }" at path "_id" for model "Poll"

const PollSchema = Schema({
title: {
    type: String,
    required: true
},
desc: {
    type: String
},
created : {
    by: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    at: {
        type: Date,
        default: Date.now
    }
}

})

Here is the testing code

describe('Associations', () => {
let _cindy, _poll;

beforeEach((done) => {
    _cindy = new User ({
        firstName : 'Cindy', 
        lastName : 'Cronkite'
    })

    _poll = new Poll ({
        title : 'my first blog', 
        desc : 'yada yada yada'
         created : {
             by : _cindy._id
        }
    })
    _poll.created = _cindy

     _cindy.save()
         .then(() => {
             _poll.save().then(() => done())
        })



})

it('saves a relation between a user and a poll', (done) => {
    Poll.findOne({ title : 'my first blog'})
        .populate('created')
        .then( (_pollQuery) => {
            console.log('_pollQuery', _pollQuery)
            assert(_pollQuery.created.by.firstName === 'Cindy')
            done()
        })
})
})

Solution

  • You need to populate with created.by

    Poll.findOne({ title : 'my first blog'})
            .populate('created.by')
    

    Instead of populate, I would suggest to use $lookup aggregation so that data is fetched within single query.