Bogdan
Bogdan

Reputation: 121

MongoDB and dynamic query building with $push statement with node.js

I'm creating an application where I need to keep version of each field in database when update is performed. So I figured that I would use statement like this to accomplish it.

 collection.update({ _id: id },
            {
                $push: { placeholder : { $each: [{ data: keyValue, timeStamp: date, editor: editorID}] } }
            },  

The placeholder is a field which might be different each time depending which field I'm updating in the table.

var key = req.body.key;
var keyValue = req.body.keyValue;
var editorID = req.body.editor;
var date = new Date();

The above variables are initialized based on the form submitted and the key is the name of the database filed which I would like to use instead of placeholder.

How can I make the placeholder to represent database field name passed from the form?

Upvotes: 1

Views: 580

Answers (1)

Bogdan
Bogdan

Reputation: 121

I found the solution.

var query = {};   
query[key] = { data: keyValue, timeStamp: date, editor: editorID };

and then

collection.update({ _id: id },
            {
                 $push:query              
             }
            },  

Upvotes: 1

Related Questions