Find User In Mongo, With Mongoose, And Return The Result To A JSON
Solution 1:
Try using JSON.parse() and JSON.stringify() to remove mongoose object property:
var myJson = {
user : User.findOne({
firstName: regex,
lastName: authorSplitedName.last
}, function (err, user){
return JSON.parse(JSON.stringify(user)));
})
}
Solution 2:
Mongoose's find
methods return their results asynchronously via the callback function. This means, the findOne
method will not give you the query's result (as obviously assumed in your sample code). In case you're using express.js, you typically do something like res.json(result)
in your callback function to send the JSON result:
router.get('/:someParameter', function(req, res, next) {
var query = {}; // your query
User.findOne(query, function(err, user) {
if (err) return next(err); // handle error case
res.json(user);
});
});
If you need a raw JSON or raw Object without any mongoose-specific properties, you can use the toJSON()
or toObject()
methods on mongoose documents.
Concerning your comment; not sure whether this was a question, but: The same applies if you search for a collection; the difference is, that your callback method will receive an array as second parameter instead of a single object.
Post a Comment for "Find User In Mongo, With Mongoose, And Return The Result To A JSON"