javascript - Update multiple documents in MongoDB by altering object in array -
i have simple application registration/login , coursera/udemy type, app lists specific courses , users can them or enroll in them. have been trying make mongodb function updates user in database , since users can courses has update courses (courses have field "usersliked", array , keep user documents have liked it).
the course structure following:
{ "_id" : objectid("5977662564aac9f6c8d48884"), "title" : "title", "lecturer" : "lecturer", "length" : 30, "coverphoto" : "photo", "usersliked": [ { "_id" : objectid("597763e346a7a463cbb8f529"), "fullname" : "name", "username" : "username", "password" : "hash", "city" : "city", "street" : "street", "website" : "website" } ], "lectures" : [ { "title" : "introduction", "number" : 1, "url" : "someurl" } ] } and user structure:
{ "_id" : objectid("597763e346a7a463cbb8f529"), "fullname" : "name", "username" : "username", "password" : "hash", "enrolledcourses" : [ ... ] } ], "city" : "city", "street" : "street", "website" : "website" } so calling function when want change. changes usercollection in coursecollection nothing, while should courses , if of them have object username(the user's username) in "usersliked" array should modify user there too.
const updateuser = (username, details) => { userscollection .update({ username: username, }, { $set: { fullname: details.fullname, city: details.city, street: details.street, website: details.website, }, }); coursescollection .updatemany( { usersliked: { $elemmatch: { username: username, }, }, }, { $set: { 'usersliked.username': details.username, 'usersliked.city': details.city, 'usersliked.street': details.street, 'usersliked.website': details.website, }, } ); };
your match on course update looks valid trying set values array , according mongo docs need provide array indexer or positional operator.
the following allow set command operate on first element within usersliked array matches given username.
coursescollection.updatemany( { usersliked: { $elemmatch: { username: username, }, }, }, { $set: { 'usersliked.$.username': details.username, 'usersliked.$.city': details.city, 'usersliked.$.street': details.street, 'usersliked.$.website': details.website }, } ) you choose element in usersliked array update e.g. usersliked.1.username suspect each course has 1 element in usersliked given username in case using $ operator (which means: first matching array element) should suffice.
Comments
Post a Comment