It’s my first post here so please let me know if there’s anything incomplete about my question, or if there’s anything else that is missing
I’m trying to make a POST request to an array in my data structure called features
:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
categoryname: {
type: String,
required: true
},
items: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
itemname: {
type: String,
required: true
},
features: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
firstfeature: {
type: String
},
date: {
type: Date,
default: Date.now
}
},
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
secondfeature: {
type: String
},
date: {
type: Date,
default: Date.now
}
}
],
date: {
type: Date,
default: Date.now
}
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Category = mongoose.model('category', CategorySchema);
When I post the following data to the array (with Postman):
Key: firstfeature, Value: test data1
Key: secondfeature, Value: test data2
It only pushes the first piece of data to the array:
"items": [
{
"features": [
{
"date": "2018-06-30T18:41:58.285Z",
"_id": "5b37cef693ed12168001ac68",
"firstfeature": "test data1",
"user": "5b2b6efe4c356e1368d73a3f"
},
{
"_id": "5b3b6868b8139f0cd08aab4a",
"user": "5b2b6efe4c356e1368d73a3f",
"date": "2018-07-03T12:13:28.130Z"
}
]
I can’t figure out what I need to change here in order to add data to the whole array, already tried category.items.features.push(newFeature)
:
router.post(
'/feature/:id/:item_id',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Category.findById(req.params.id)
.then(category => {
const newFeature = {
firstfeature: req.body.firstfeature,
secondfeature: req.body.secondfeature,
user: req.user.id
};
// Add to item array
category.items[0].features.push(newFeature);
// Save
category.save().then(category => res.json(category));
})
.catch(err => res.status(404).json({ itemnotfound: 'Item not found'
}));
}
);
router.post(
'/feature/:id/:item_id',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Category.findById(req.params.id)
.then(category => {
const newFeature = {
firstfeature: req.body.firstfeature,
secondfeature: req.body.secondfeature,
user: req.user.id
};
// Add to item array
category.items[0].features.push(newFeature);
// Save
category.save().then(category => res.json(category));
})
.catch(err => res.status(404).json({ itemnotfound: 'Item not found'
}));
}
);