Reputation: 1
Could you please help me. I am following this tutorial: "Managing Orders with Mongoose | Creating a REST API with Node.js" https://www.youtube.com/watch?v=VKuY8QscZwY&list=PL55RiY5tL51q4D-B63KBnygU6opNPFk_q&index=8 It is quite old (2017) but still good I think. But I got stuck (about 8 min.). Doing a POST request the same way as in the tutorial leads me to an Error. I have read previous topics like this, comments under the video, but I did not find the answer. Here is the code:
Order Scheme
const mongoose = require('mongoose');
const orderSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
required: true,
},
quantity: { type: Number, default: 1 },
});
module.exports = mongoose.model('Order', orderSchema);
Product Scheme
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
price: { type: Number, required: true },
});
module.exports = mongoose.model('Product', productSchema);
Post Order Route
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Order = require('../models/order');
router.post('/', (req, res, next) => {
const order = new Order({
_id: mongoose.Types.ObjectId(),
quantity: req.body.quantity,
product: req.body.productId,
});
order
.save()
.then((result) => {
console.log(result);
res.status(201).json(result);
})
.catch((err) => {
console.log(err);
res.status(500).json({
error: err,
});
});
});
Request
POST http://localhost:3000/orders
Content-Type: application/json
{
"quantity": "10",
"poductId": "5fae9023c8e7ac3e54ae6752"
}
I am getting:
Error: Order validation failed: product: Path `product` is required.
{
"error": {
"errors": {
"product": {
"name": "ValidatorError",
"message": "Path `product` is required.",
"properties": {
"message": "Path `product` is required.",
"type": "required",
"path": "product"
},
"kind": "required",
"path": "product"
}
},
"_message": "Order validation failed",
"message": "Order validation failed: product: Path `product` is required."
}
}
Upvotes: 0
Views: 1063
Reputation: 2011
Looks like there is a typo in your request JSON
{
"quantity": "10",
"poductId": "5fae9023c8e7ac3e54ae6752" ---> change this to productId (missing `r`)
}
Upvotes: 1