I have the following schemas:
// ingredient var ingredSchema = new Schema({ name: String, cost: Number }); // order var orderSchema = new Schema({ cusName: String, ingredients: [{type: Schema.Types.ObjectId, ref: 'Ingredient'}] }); // create model var Ingredient = mongoose.model('Ingredient', ingredSchema); var Order = mongoose.model('Order', orderSchema);
I have already saved a bunch ingredients in a collection ingredients
and have a UI where users choose a set of ingredients for their burgers. I then try to save an order for a burger in another collection orders
within the same database burgers
like this:
// get order info from the form var newOrder = new Order({ cusName: req.body.name, ingredients: req.body.ingredients }); newOrder.save(function(err) { if (err) return console.log('Could not save your new order', err); res.redirect('/order'); });
The call to save an order generates the following error:
{ message: Cast to ObjectId failed for value xxx at path 'ingredients', name: 'CastError', type: ObjectId, value: xxx, path: 'ingredients' }
I use mongoose version 3.6.11. Please help me hack this.
PS: req.body.ingredients is an array built from checkboxes.
To get the object ID after an object is saved in Mongoose, we can get the value from the callback that's run after we call save . const { Schema } = require('mongoose') mongoose. connect('mongodb://localhost/lol', (err) => { if (err) { console. log(err) } }); const ChatSchema = new Schema({ name: String }); mongoose.
ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.
Mongoose save with an existing document will not override the same object reference. Bookmark this question.
There are 2 possible problems with your code right now:
1. req.body.ingredients
will not be an array of ObjectId
s, and mongoose wants it alright (I doubt of this one).
You should cast every ingredient to ObjectId
first. Supposing req.body.ingredients
is array, then you would do something like this:
var casted = req.body.ingredients.map(function( ingredient ) { return mongoose.Types.ObjectId(ingredient); });
I did not tested this, see if it'll work for you.
2. Mongoose is trying to cast your ingredients, but one of them is not a valid ObjectId
ObjectId
should be composed of 24 hex chars, check whether you're passing values like this to Mongoose.
Please, post the result if one of them work for you :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With