1

I am querying a document from Mongo DB using Mongoose:

    const dbObj = await User.findOne({ "_id": id});

From there, I am attempting to turn that object into a string:

    const dbObjStr = JSON.stringify(dbObj);

The problem: JSON.stringify isn't properly converting the object to a string, the outcome looks like this:

    {"accreditedStatus":3,"count":39}

How can I get it to convert to an actual string? Like this:

    "{\"accreditedStatus\":3,\"count\":39}"

Environment: Node.js v10.16.0, NPM 6.10.0, Mongo DB 4.0.10, Mongoose ^5.3.7

1 Answer 1

1

stringify is working. dbObjStr contains a string. The \" escape characters you are looking for are not part of the string. You can observe what is going on more clearly by separating your string into an array of single-character strings.

console.log(dbObjStr.split(''))

If for whatever reason you would like dbObjStr to contain the escaped characters, just run stringify twice:

 const dbObjStr = JSON.stringify(JSON.stringify(dbObj));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.