Snymax
Snymax

Reputation: 357

iterate through mongodb entry javascript node

I am trying to iterate through a doc during my update function

User.prototype.update = function(user, done){
    this.model.findOne({_id:user._id}, function(err, doc){
        console.log(doc);
        for(var i in doc){
            if(user[i] != undefined && user[i] != doc[i]){
                console.log('this value', i, user[i], user[i] === doc[i], doc[i]);
                doc[i] = user[i];
            }
        }
        console.log(doc[i]);
        //doc.save(done);
    });
}

however doing this catches all the functions that the model has added to the object such as _save, _done, _events, and many other fields that i dont care to check.

I also tried adding a if(user.hasOwnProperty(i)) but that doesnt work.

UPDATE: this is working pretty nicely if anyone sees a better way to go about it let me know

User.prototype.update = function(user, done){
    this.model.findOne({_id:user._id}, function(err, doc){
        for(var i in doc._doc){
            if(user[i] && user[i] != doc[i])
                doc[i] = user[i]
        }
        doc.save(done);
    });
}

Upvotes: 0

Views: 417

Answers (2)

Ken Penn
Ken Penn

Reputation: 766

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

keys = Object.keys(doc); // returns an array of keys

keys.forEach(function(key{
  if (typeof doc[key] !== 'function' && user[key] && doc[key] !== user[key] ) {
    // do what you want here
  }
})

That should get you started. If doc[key] or user[key] is an object, they won't be equal. Google 'javascript object equality' to find a solution that work for you.

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77522

In you case, query returns MongooseDocument, that's why you get properties like _doc, save and so on, you should use lean - if you use this function you get plain js object not MongooseDocument..

this.model.findOne({_id:user._id}).lean().exec(function(err, doc){
     // ..
});

Or use toObject

this.model.findOne({_id:user._id}, function(err, doc){
    for (var i in doc.toObject()) {
       console.log(i);
    }
});

Upvotes: 2

Related Questions