简体   繁体   中英

How to construct a dynamic update query in Nodejs for Mongodb?

I want to create a dynamic query that updates a document in a Mongodb collection based on the user input. The user may update some or all the fields in the document. The document also contains an array to which the user is allowed to add elements. I know how to construct simple dynamic queries for 'find' queries but struggling with an update query which might have $set , $addToSet , $pull etc elements.

My final query will look like this:

Col.update({'_id' : bookId}, {$inc : {'total_count' : 1}, $set: {'name': name}, $addToSet : {'reviewed_by' : user}})

All the elements in the update part of the query will be added conditionally.

I have searched on SO and elsewhere and I don't see any example that shows how to accomplish this. Hopefully many others will also find this useful.

Not sure I'm understanding you correctly, but it sounds like what you're looking for is really just javascript...

var update = {};
if( ... ) // do increment?
    update['$inc'] = {'total_count': 1};

// and so on...

if(Object.keys(update).length)
    Col.update({'_id': bookId}, update);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM