I am building a REST Api with express, mongodb and mongoose. As a part of my schema I have stated that I want an array to hold a list of values. I am unable to use postman to add or update the values in the array. I am basically wondering why this isn't working and what would be the best practice for this type of situation.
Here is my mongoose Schema
const Schema = mongoose.Schema;
let Quote = new Schema({
name: {
type: String,
},
quote: [String],
date_submitted: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('Quote', Quote);
As Stated I have an Array setup to hold multiple quotes.
Here is the method for adding a quote to the mongoDB:
let quote = new Quotes({
name: req.body.name,
quote: req.body,
});
quote
.save()
.then(quote => {
res.status(200).send('adding new quote successful');
})
.catch(err => {
res.status(400).send('adding new quote failed' + err);
});
});
This does add a record to the DB but I am not sure if this method is best practice.
This is the update method that is NOT working at all
router.post('/update/:id', (req, res) => {
// Quotes.findOneAndUpdate({ name: req.body.name }, { $push: { quote: req.body.quote } });
Quotes.findById(req.params.id, function(err, quote) {
if (!quote) {
res.status(404).send('Data is not found');
} else {
quote.author = req.body.name;
quote.quotes = { $push: { quote: req.body.quote } };
quote.date_submitted = req.body.date_submitted;
quote
.save()
.then(quote => {
res.json('quote updated');
})
.catch(err => {
res.status(400).send('Update not possible' + ' ' + err);
});
}
});
});
You can see that I tried to do the findOneAndUpdate method but it did not push the values into the array like it should. When I submit my POST request from Postman I do not get an error but when I check the Database the Array value remains the same. Any help on this would be amazing!