I'm working with NodeJS and Mongoose, it's a shopping cart. I'm getting an error during posting the order.
This is the error output:
Error: Order validation failed: user.userId: Path `user.userId` is required.
at ValidationError.inspect (/opt/sourcecode/sandboxnodejs/node_modules/mongoose/lib/error/validation.js:48:26)
at formatValue (node:internal/util/inspect:763:19)
at inspect (node:internal/util/inspect:340:10)
at formatWithOptionsInternal (node:internal/util/inspect:2006:40)
at formatWithOptions (node:internal/util/inspect:1888:10)
at console.value (node:internal/console/constructor:323:14)
at console.log (node:internal/console/constructor:359:61)
at /opt/sourcecode/sandboxnodejs/controllers/shop.js:108:29
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
errors: {
'user.userId': ValidatorError: Path `user.userId` is required.
at validate (/opt/sourcecode/sandboxnodejs/node_modules/mongoose/lib/schematype.js:1277:13)
at /opt/sourcecode/sandboxnodejs/node_modules/mongoose/lib/schematype.js:1260:7
at Array.forEach (<anonymous>)
at ObjectId.SchemaType.doValidate (/opt/sourcecode/sandboxnodejs/node_modules/mongoose/lib/schematype.js:1210:14)
at /opt/sourcecode/sandboxnodejs/node_modules/mongoose/lib/document.js:2700:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'user.userId',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'Order validation failed'
}
This is the link to the gist: https://gist.github.com/hftamayo/bba430df7070bf6d141aeddcbb698716
The main method in the controller that trigger this error is this:
exports.postOrder = (req, res, next) => {
req.user
.populate("cart.items.productId")
.then((user) => {
const products = user.cart.items.map((i) => {
return { quantity: i.quantity, product: { ...i.productId._doc } };
});
const order = new Order({
user: {
name: req.user.name,
userId: req.user.userId
},
products: products,
});
return order.save();
})
.then((result) => {
return req.user.clearCart();
})
.then(() => {
res.redirect("/orders");
})
.catch((err) => console.log(err));
};
the repo is this one: https://github.com/hftamayo/sandboxnodejs/tree/chapt12_mongoose
Other components involved are:
shop.js (controller)
user.js (model)
order.js (model)
I have several days trying to debug it, I know the userId is null but I'm not getting why, any hints will be highly appreciated.
Best wishes
The bug was about an undefined parameter (userId):
user: {
name: req.user.name,
userId: req.user.userId
},
So, this did the trick:
user: {
name: req.user.name,
userId: req.user._id
},