MALON
MALON

Reputation: 742

I don't know how to print mongodb query results using the nodejs native driver

I'm storing a single word in the database using the following:

collection.update({},{$set:{word:newWord}},{upsert:true},function(){
    collection.find().nextObject(function(err, results) {
        oldWord = results;
        console.log("New Word: " + results);
    });
});

here is an example of my DB

{ "_id" : ObjectId("4ff92def446ce41df5692385"), "word" : "asdf" }

Every time it gets to the console.log line, it looks like:

New Word: [object Object]

I'm trying to isolate "asdf" (sans quotes) from the above record. I've tried everything from toArray, nextObject, etc.

What am I missing? I've been trying for hours!

Upvotes: 4

Views: 5641

Answers (3)

nicb
nicb

Reputation: 321

In node, you can just use: console.log("New Word: ", results); (note the comma).

Another option: console.log( JSON.stringify(results) );

It will print something like: { "_id" : "4ff92def446ce41df5692385", "word" : "asdf" }

I don't really agree that the "string representation of objects in Javascript isn't very helpful." I find it helpful, at least.

Upvotes: 2

gherkins
gherkins

Reputation: 14983

You can either override the toString Method of you result object as described here: http://blog.anselmbradford.com/2009/04/05/object-oriented-javascript-tip-overriding-tostring-for-readable-object-imprints/ or simpy just print the property you want to show by specifying it object.propertyname.

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

If you're interested in some field, you should print that, not the whole object (mainly because string representation of objects in Javascript isn't very helpful).

 console.log("New Word: " + results.word);

Upvotes: 4

Related Questions