I'm trying to add a new nested Item document to a documents array in the List document. Instead of adding the Item document to the array, it overwrites the existing documents and replaces them with the new one.
Here's the code:
app.post('/', async (req, res) => {
const item = req.body.item;
const newItem = new Item({
name: item,
});
// Takes the value from the submit button
const list = req.body.list.toLocaleLowerCase();
await List.updateOne({ name: list }, { items: newItem });
res.redirect('/');
});
This is the rest of the code that interacts with the List:
const itemsSchema = new Schema({
name: { type: String, required: [true, `The field name is required.`] },
});
const listsSchema = new Schema({
name: {
type: String,
required: [true, `The name of the list is required.`],
},
items: [itemsSchema],
});
const List = mongoose.model('List', listsSchema);
app.get('/:list', async (req, res) => {
// Get the requested title by the user and lower case it.
const titleRequested = req.params.list.toLocaleLowerCase();
// Upper case the first letter.
const upperCasedTitle =
titleRequested.at(0).toLocaleUpperCase() + titleRequested.slice(1);
// Find if the list with the requested title exists in the database.
await List.findOne({ name: titleRequested }).then(async list => {
if (!list) {
const newList = new List({
name: titleRequested,
items: new Item({
name: `You've created a ${titleRequested} list!`,
}),
});
await newList.save();
await List.findOne({ name: titleRequested }).then(document => {
res.render('list', {
// De aca sale el value="<%= title %>"
title: upperCasedTitle,
items: document.items,
});
console.log(`${upperCasedTitle} list created succesfully.`);
});
} else if (list) {
await List.findOne({ name: titleRequested }).then(document => {
res.render('list', {
// value="<%= title %>"
title: upperCasedTitle,
items: document.items,
});
});
}
});
});
Is there any way to update the List document found by the query and not overwrite the existing nested documents?
If there is a specific Model.prototype function that does this, I haven't found it :(