dman
dman

Reputation: 11074

Node- Can't attach key/value to object

Using Node. This is weird, I am not able to attach a key/value....broadcastStamp = date to the object result. I verified with typeof it is a object. There is no error...the key/value is just simply not there.

function broadcastSingleClient(result, event, httpObject) {
    var date = new Date().valueOf();
    result.broadcastStamp = date; 
    console.log(result);

UPDATE: This object is coming from a mongoose/mongodb query call back function:

Object.keys(models).forEach(function (model) {
    models[model].find({}).sort({_id: -1}).limit(1).exec(
        function (err, result){
            broadcastSingleClient(result[0], model+"Result", res);
        });

When doing this query in the shell without the exec() call back, I am able to attach to the object.

Upvotes: 1

Views: 95

Answers (2)

Iftah
Iftah

Reputation: 9572

Do you intend to save the result after you modify it?
Are you using Mongoose virtual properties in your broadcastSingleClient function ?

if not then I think you can use lean which will return plain js object - without the Mongoose object wrapping it.

Try this:

Object.keys(models).forEach(function (model) {
models[model].find({}).sort({_id: -1}).limit(1).lean().exec(      // note the "lean"
    function (err, result){
        broadcastSingleClient(result[0], model+"Result", res);
    });

Upvotes: 1

Artem Volkhin
Artem Volkhin

Reputation: 1372

I created jsfiddle and it works -- http://jsfiddle.net/volkhin/YGgzL/, I only added result object as var result = {a: 1, b: 2};. The only things that comes to my mind is that result is not simple object. It definitely will not work for null, undefined, numbers and so on.

Edit: Then I believe it's due to getters/setters. And it would be better to avoid modifying such object because modifying it can lead to unknown consequences inside mongoose. If you just need to access some data in this object you can try create shallow copy (for example, using underscorejs _.clone or manually iterating over its keys) which will return simple object. Which you can modify, of course. But I'm not sure if it will contain all the data -- again, it might heavily depend on getters/setters.

Upvotes: 1

Related Questions