I am very new to MEAN projects and most of my code is code from various tutorials adapted to my own needs with my limited knowledge of MEAN. Sorry for any misuse of terminology, I'll try to explain my situation the best I can.
I have a MongoDB database with two collections: items
and carts
. items
has documents that have fields for the Product, Color, Size, and Price of each item
. carts
has documents with one field that is an array of items
referencing the ObjectId for each item
, a field for the Total, and a boolean field called Active.
I'm struggling with the POST request to the cart
API that includes references to the ObjectId of multiple items
.
item.model.js:
module.exports = mongoose => {
const Item = mongoose.model(
'item',
mongoose.Schema({
product: {
type: String,
required: true
},
color: {
type: String,
required: true
},
size: {
type: String,
required: true
},
price: {
type: Number,
required: true
}
})
);
return Item;
};
cart.model.js:
module.exports = mongoose => {
const Cart = mongoose.model(
'cart',
mongoose.Schema({
items: [{
item: {
type: mongoose.Schema.Types.ObjectID,
ref: 'Item'
}
}],
total: {
type: Number,
required: true
},
active: {
type: Boolean,
required: true
}
})
);
return Cart;
};
cart.controller.js cart creation:
const db = require('../models');
const Cart = db.carts;
// Create and Save a new Cart
exports.create = (req, res) => {
// Validate request
if (!req.body.items) {
res.status(400).send({ message: 'Content can not be empty!' });
return;
}
// Create a Cart
const cart = new Cart({
items: req.body.items,
total: req.body.total,
active: req.body.active ? req.body.active : true
});
// Save Cart in the database
cart
.save(cart)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || 'Some error occurred while creating the Cart.'
});
});
};
I figured it out lol.
Formatting the POST request like this successfully added items to the items
field array:
{
"items": [
{"item": "616f3f378302f3944caa8fac"},
{"item": "6182ff5cd852c5a4c7315048"},
{"item": "6182ff6ad852c5a4c731504c"}
],
"total": 0,
"active": true
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.