0

I want build a simple function which can update (upsert) a document by collection name, field key, field value, updateData

example:

function updateDB(tableName, id, rowInfo, checkfield, callback) {
db.collection(tableName, function (err, collection) {
    if (err) {
        console.log(err);
    } else {

        console.log(checkfield);
        collection.update({ checkfield: id }, rowInfo, { upsert: true }, function (err, objects) {
            if (err) {
                throw err;
                callback(false);
            } else {
                //  console.log(objects);
                callback(true);
            }
        });
    }
});}

However when I use parameter as field filter in update query it always inserts new data an does not update the document. Example:

collection.update({ checkfield: id }.....

But when I change the field filter to realFieldName it works correctly. Example:

collection.update({ 'realFieldName': id }....

What is the difference between the two?

First Zero
  • 21,586
  • 6
  • 46
  • 45
maxyen
  • 129
  • 1
  • 6

1 Answers1

0

you should code it like:

var filter = {};
filter[checkfield] = id;
collection.update(filter, ...);

define an object like { checkfield: id }, checkfield is regarded as an identifier NOT a variable.

for details, please refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime)

kite.js.org
  • 1,599
  • 10
  • 11