I have an item schema and a category schema. When I create a new item I save the category object id within the item schema. That works fine, but my solution was not well thought out. The question is how do I save the product object ID within all the categories that were selected for the item, simultaneously, while the product is being saved?
Item Schema
var itemsSchema = new Schema({
item: String,
cats: [{type: Schema.Types.ObjectId, ref: 'catSchema'}],
productID: String,
price: String,
image: String,
sizes: Array,
description: String,
weight: Number
});
Category Schema
var catSchema = Schema({
_products : [{ type: Schema.Types.ObjectId, ref: 'itemsSchema' }],
name : String,
slug : String
});
Add Item Route
router.post('/add/items', function(req, res) {
if (req.session.passport.user == undefined) {
res.json({
'message': 'You can\'t do that'
});
} else {
theUser.find({
username: req.user.username
}, function(err, data) {
if (data[0].type != 'admin') {
res.json({
'message': 'You can\'t do that'
});
} else {
var theImage = '';
if(typeof req.files != 'undefined' && typeof req.files.image != 'undefined') {
theImage = req.files.image.name;
fs.readFile(req.files.image.path, function (err, data) {
imageName = req.files.image.name
/// If there's an error
if (!imageName) {
console.log("There was an error")
imageName = '';
} else {
var newPath = '/path/to/folder' + imageName;
/// write file to uploads/fullsize folder
fs.writeFile(newPath, data, function (err) {
});
}
});
}
//var catArray = [];
var catArray = req.param('catArray');
var weight = parseFloat(req.param('weight'));
// save info to database
var newItem = new Item({
item: req.param('item'),
price: req.param('price'),
productID: Math.round(Math.random() * 9999999999999999).toString(),
image: theImage,
description: req.param('description'),
cats: catArray,
//sizes: sizeArray,
weight: weight
});
newItem.save(function(err) {
if (err) {
console.log(err);
} else {
Item.find(function(err, items) {
if (err) {
return console.log(err);
} else {
res.json({
items: items
});
}
});
}
});
}
});
}
});