Reputation: 955
Trying to setup a mongoose database for a Node Express application, some of my documents have records that need to reference other collections.
I'm aware that Mongoose provides the populate
method for filling these sort of relations, but I'm having difficulty setting it up. As far as I can see, I need to specify my schema as so...
bookingSchema = mongoose.Schema
_id: Number
# Involved users
__booker: {type: Schema.Types.ObjectId, ref: 'User'}
...but when I attempt to seed the database with __booker values such as 1, 2, 3 (all of which are valid documents in the User collection) get the error...
Cast to ObjectId failed for value "3" at path "__booker"
I would assume integers or integer strings should be easily coerced to an ObjectId, but can't seem to get this working. What am I doing wrong?
Upvotes: 1
Views: 340
Reputation: 955
I've written this question as the above situation froze me for hours. Massive irritation and it turns out the solution is quite simple and inside the mongoose docs, just as a single one liner. Can't imagine I'm the only one encountering this though, hence posting the answer.
It would appear that mongoose won't be happy with casting your types for _ids. People are likely to run into this problem if they are creating databases that have seeded values that specify relations to each other. I was trying to seed with the Number type as my reference to the other models, as I believed mongoose would cast that to the correct type for the ids. It won't.
If a User looks like this...
userSchema = mongoose.Schema
_id: Number
fname: String
...and your post looks like this...
postSchema = mongoose.Schema
_id: Number
__user: {type: Number, ref: 'User'}
Then you need to give this as your UserSchema.
bookingSchema = mongoose.Schema
_id: Number
# Involved users
__booker: {type: Number, ref: 'User'}
Note the type is Number, not ObjectId. This will allow the populate function to operate correctly on your model instances.
Hope this helps, I'm off to hit my head against the wall!
Upvotes: 1