I am trying to append an object to an array in an existing mongodb document (categories: []). The server is able to receive the request body but it gives { acknowledged: false } when I log the update updatedCategory. The document isnt updated either.
seller.js
const express = require('express');
const router = express.Router();
const User = require('../models/user');
const Menu = require('../models/menu');
router.put('/menu/initiate', async(req, res) => {
const user = await User.findOne({email: req.body.user_email})
const user_id = user._id.valueOf()
const updatedCategory = await Menu.updateOne({user_id: user_id}, {$push: {categories: {category: req.body.categoryName, items: []}}})
console.log(updatedCategory)
res.status(200).send('category updated')
})
module.exports = router;
Menu Model:
const Menu = new mongoose.Schema({
"user_id": {
"type": "String"
},
"menu": {
"categories": {
"type": [
"Mixed"
]
}
}
},
{collection: 'menus'});
On the Menu model, the categories field is nested under the menu field. In your update document, it is treated as a top-level field, which doesn't match with the defined Schema. Because the update you're trying to perform doesn't correspond to a field in the schema, Mongoose doesn't attempt an update at all. That's likely why we aren't seeing other fields we might expect when attempting an update, such as matchedCount.
I believe the update will work if you make sure that you are pushing to menu.categories like this:
const updatedCategory = await Menu.updateOne({user_id: user_id}, {$push: {"menu.categories": {category: req.body.categoryName, items: []}}})