V
V
Vasily Koryak2015-01-19 13:36:02
JavaScript
Vasily Koryak, 2015-01-19 13:36:02

How to pass field name to mongoDB (mongoose) update function?

There is a collection

{
    "email" : "[email protected]",
    "hash" : "$2a$10$XAEnbgWFsEAICSsI66jR9u2VMZhfLwp54n2CmR2xp5M1qJcGOe8ze",
    "salt" : "$2a$10$XAEnbgWFsEAICSsI66jR9u",
    "_id" : ObjectId("54b3892c4d165ad054b29477"),
    "name" : {
        "first" : "test",
        "last" : "test"
    },
    "__v" : 0
}

/* 1 */
{
    "__v" : 0,
    "_id" : ObjectId("54a143f4af6053f026119265"),
    "email" : "[email protected]",
    "hash" : "$2a$10$oj5Z54mYYOJQ8WcRUpsxwOIRA.XHsXjp5hsqq4PfTmLjnFpUC18qq",
    "name" : {
        "first" : "test1",
        "last" : "test1"
    },
    "salt" : "$2a$10$oj5Z54mYYOJQ8WcRUpsxwO"
}

The model is as follows:
var UserSchema = new Schema({

    // Name
    name : { 
        first: { type: String, required: true },
        last: { type: String, required: true }
    },
    group : {type : String, required: true},
    contactNum: {type: Number, required: false},
    email: { type: String, required: true, unique: true },
    salt: { type: String, required: true },
    hash: { type: String, required: true },
    visits: {
        lastVisit:  {type: Date, required:false},
        allVisits: {type: Date, required:false}
    },
    // Address
    address : {       
        address1: {type:String, required:false},
        town: {type:String, required:false},
        province: {type:String, required:false},
        country: {type:String, required:false},
        pcd: {type:String, required:false}
    },
    shoppingHistory: {
        product : {type:String, required:false},
        date : {type: Date, required:false}
    },
    bonusPoints : {type: Number, required:false},
    referalLink : {type: String, required:false}
  });

I'm trying to write a function to update a document:
updateUser: function (userId, data, param) {
        User.update ({_id: userId}, {
            data : param}, function(err){
            if (err) {throw err;}
        });
    },

Function launch:
db.updateUser("54a143f4af6053f026119265", "bonusPoints", 40);

The problem is that the data parameter is not passed to the update function (bonusPoints), instead the update function tries to update the data field, which does not exist.
How to pass a field name when running a function?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Shikanov, 2015-01-19
@quaZZy

You cannot pass an attribute name in a variable to an object literal.
This is how it will work:

updateUser: function (userId, data, param) {
        var key_value = {};
        key_value[data] = param;
        User.update ({_id: userId}, key_value, function(err){
            if (err) {throw err;}
        });
    },

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question