'How to assign a value to a key within an array?
I am trying to add the about, link values into the description array defined in the schema and then use the .save() function to save it to the database. Any help would be appreciated. Thank You.
router.post('/:name/description',async(req, res)=>{
const project = await Project.findOne({name: req.params.name})
if (!project) {
return res.status(404).send('project doesn\'t exist. Check URL');
} else {
const {about, link} = req.body.description;
console.log(project);
}
});
Schema:
const projectSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true
},
main_image: {
type: Buffer
},
description:[{
about: {
type: String
},
github_link: {
type: String
}
}]
});
Solution 1:[1]
Try using push:
router.post('/:name/description',async(req, res)=>{
const project = await Project.findOne({name: req.params.name})
if (!project) {
return res.status(404).send('project doesn\'t exist. Check URL');
} else {
const {about, link} = req.body.description;
project.description.push({ about, github_link: link });
await project.save();
return res.status(201).send('Description added to project');
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lpizzinidev |
