I’m trying to run this piece of code:
router.put('/restaurants/:id', async (req, res) => { try { const response = await Restaurant.findByIdAndUpdate(req.params.id, {name: req.body.name, item_1.name: req.body.item, item_2.name: req.body.item_2, item_3.name: req.body.item_3, item_4.name: req.body.item_4 }) res.send(response) } catch (error) { res.send(error) } })
where the scenario is I have items (i.e item_1 etc) saved as objects in database, items got two properties name and rating, when admin wants to edit an item it should only be able to just edit the name property of an item not the rating, so for implementing this what i’m trying to do is, upon edit request as shown here, I want to set only the name property of an item as same to what has been sent in the request. but it gives me a typescript error (though I don’t have typescript installed) saying:
',' expected.ts(1005)
and it happens before running this code, actually vs code is showing this error. and upon running it is showing something like this:
E:xordsecond_assignmentnoderoutesrestaurants.js:50 item_1.name: req.body.item, ^ SyntaxError: Unexpected token '.' at wrapSafe (internal/modules/cjs/loader.js:1054:16) at Module._compile (internal/modules/cjs/loader.js:1102:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Module.require (internal/modules/cjs/loader.js:1026:19) at require (internal/modules/cjs/helpers.js:72:18) at Object.<anonymous> (E:xordsecond_assignmentnodeindex.js:8:21) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 [nodemon] app crashed - waiting for file changes before starting...
same thing happens with a different error when i try to access the object property with bracket notation.
I apologise for the very long query but I’m wondering; is the syntax I’ve used in this code for setting the value of an object’s key inside another object, incorrect? if so then why? also what would be the alternative way to do this?
Advertisement
Answer
thanks God! in mongoose v5.10.19 documentation I saw almost the same instance where they use a property of an object as a key of another object here:
Parent.update({}, { 'child.name': 'Luke Skywalker' }, (error) => { // Error because parentSchema has `strict: throw`, even though // `childSchema` has `strict: false` });
by which I learnt that in such cases one should wrap the key in quotes as they did in “child.name”. and that resolved the issue i was facing.