- My goal is: pushing an object which is created by user via form to an subcollection that is also created by the user.
- My actions are: I’ve created subcollection(named “category”) endpoint and list them in the form which user can create object(named “product”) and pick a category .But i couldnt achieve to post endpoint for adding a product under the selected category.
My Models:
const mongoose = require(“mongoose”);
const menuSchema = mongoose.Schema({
company: { type: mongoose.Schema.Types.ObjectId, ref: “Company” },category: [
{
name: String,
products: [
{
name: String,
price: Number,
description: String,
state: Boolean,
imgUrl: String
}
]
}
]
});
module.exports = mongoose.model(“Menu”, menuSchema);
const mongoose = require(“mongoose”);
const companySchema = mongoose.Schema({
companyName: String,
email: String,
password: String,
adress: String,
Phone: Number,
contractNo: String,
menu: [
{
type: mongoose.Schema.Types.ObjectId,
ref: “Menu”,
category: [{ type: mongoose.Schema.Types.ObjectId, ref: “Menu” }]
}
],
createdAt: { type: Date, default: Date.now() }
});module.exports = mongoose.model(“Company”, companySchema);
EndPoint for adding product that i couldnt get successful result
AddProduct(req, res) {
const body = {
name: req.body.name,
price: req.body.price,
description: req.body.description,
imageUrl: req.body.image,
state: req.body.state
};Menu.find({ company: req.company._id }, (err, founds) => { const CatId = req.body.category; const data = founds[0].category; for (let i = 0; i < data.length; i++) { if (data[i]._id == CatId) { console.log(CatId); Menu.update( { products: data[i].products }, { $push: { products: body } }, { new: true } ) .then(info => { res.status(httpStatus.CREATED).json({ message: "created", info }); console.log(info); }) .catch(err => { res .status(httpStatus.INTERNAL_SERVER_ERROR) .json({ message: "add-product error", err }); }); } } });
},
-
The result I see is: 1. {message: “created”, info: {…}}
-
info:
1. n: 0
2. nModified: 0
3. ok: 0
4. __proto__: Object
- message: “created”
- proto: Object
- My expectation & question is: How can i code an endpoint to push a product object to under selected category by user.