Skip to content Skip to sidebar Skip to footer

Javascript Object Printing As Object Object

I am very new to both node and mongo db.I was creating a connection from node to Mongo and trying the CRUD Operations.My operations are defined in operations.js and i am calling th

Solution 1:

[object Object] is the default/automatic string conversion for an object.

So, if you use an object anywhere in a string manipulation expression such as this:

let x = {greeting: "hello"};
let str = "I would like to say the greeting " + x;
console.log(str);

Then, the JS interpreter will try to convert your object x to a string and that default string conversion will be [object Object] so you will get a result of:

 I would liketo say the greeting [objectObject]

What you need to do is either avoid using a Javascript object anywhere in a string expression or explicitly convert the object to JSON with JSON.stringify() before involving it in a string expression.

I would replace this:

console.log("Inserted " + result.result.n + "documents inserted into the collection"+collection);

with this:

console.log("Inserted ",  result.result.n, "documents inserted into the collection", collection);

Then, you're passing whole objects to console.log() and it will do its normal object display on them rather than let JS try to auto-convert them to a string.

You could also manually convert those objects to string form with JSON.stringify(result.result.n) and then use them in string expressions.

Solution 2:

Can you try with JSON.stringify(result)

like this

dboper.insertdocument(db,{"name":"Vadonut","description":"Test Vadonut"},'dishes',(result)=>{
        console.log('Insert Document:\n'+JSON.stringify(result));

        dboper.finddocument(db,'dishes',(result)=>{
           console.log("Found Documents :\n"+JSON.stringify(result));
    })

Solution 3:

It is because of two different behavior of console log with "," and "+".

let user = {"_id":"5ea4843b0f28320524d23f14", "name":"Vadonut"};
  
console.log("doc"+ user)

console.log("doc", user)

Also the check this

Post a Comment for "Javascript Object Printing As Object Object"