我有两个模型和两个路由文件。但是对象内部的一个属性不返回任何东西。
// orders.js route
const mongoose = require('mongoose');
const Order = require('../models/order');
orderRouter.route('/')
.post((req, res, next) => {
const order = new Order({
_id: mongoose.Types.ObjectId(),
quantity: req.body.quantity,
product: req.body.productId
});
order
.save()
.then(result => {
res.status(201).json(result);
})
.catch(err => {
res.status(500).json({
error: err
});
});
});
// order.js Model
const mongoose = require('mongoose');
const orderSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
// without required: true working but not returning anything
product: { type: mongoose.Schema.Types.ObjectId, ref:'Product', required: true},
quantity:{ type: Number, default:1 }
});
module.exports = mongoose.model('Order', orderSchema);
// product.js model
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);
// products.js route
const mongoose = require("mongoose");
const Product = require("../models/product");
productRouter
.route("/")
.get((req, res, next) => {
Product.find()
// SELECT SPECIFIC FIELDS TO DISPLAY
.select('name price _id')
.exec()
.then(docs => {
const response = {
// To display item conts
count: docs.length,
// To display array of selected items
products: docs.map(doc => {
return {
name: doc.name,
price: doc.price,
_id: doc._id,
request: {
type: 'GET',
url: 'http://localhost:3000/products/' + doc._id
}
}
})
};
res.status(200).json(response)
})
.catch(err => {
res.status(500).json({
error: err
})
})
})
.post((req, res, next) => {
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price
});
product
.save()
.then(result => {
console.log(result);
res.status(200).json({
message: "Created Product successfully",
createdProduct: {
name: result.name,
price: result.price,
_id: result._id,
request: {
type: 'GET',
url: 'http://localhost:3000/products/' + result._id
}
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
});
如果我在订单模型中插入required:true,那么我将得到这样的错误。 Path product is required. name": "ValidatorError"
。我不知道我在做什么错。未经模型验证。我可以发布并获取ID,数量但产品没有运气。
答案 0 :(得分:0)
您的POST看起来如何?
` 开机自检http://localhost:8000/orders 内容类型:application / json
{ “ productId”:“ 5e8b7ab88466300b9c720e68”, “数量”:“ 10” } `
您的POST请求中应该包含“ productId”和“ quantity”。