I'd need some help on setting up my rest routes in Node + Express.
My problem is as follows:
controller.js:
module.exports = {
findAll: function(req, res) {
var users = User.findAll();
res.json(users);
}
};
User.js:
module.exports = {
findAll: function(req, res) {
userModel.user.find(function(err, user) {
if (!err) {
console.log(user);
} else {
console.log(err);
}
});
}
};
This console.logs me the users as expected, but if I change the console.log bit to return:
findAll: function(req, res) {
return userModel.user.find(function(err, user) {
if (!err) {
return user;
} else {
return console.log(err);
}
});
}
it gives me an error:
TypeError: Converting circular structure to JSON at Object.stringify (native) at ServerResponse.res.json...
I don't see where I would have any circular structures.. I'm using Mongoose and, like said, everything works ok as long as I only console.log the userlist, but as soon as I try to return it to my controller it fails... What am I not seeing here?
You cannot just return a value inside an asynchronous execution context
The problem is with this line:
var users = User.findAll();
User.findAll();
returns a query object (before the request even happens).
so res.json(users);
tries to stringify the query object which has circular structure.
Query#find([criteria], [callback])
Finds documents.
Parameters:
[criteria]
<Object>
mongodb selector
[callback]
<Function>
Returns:
<Query>
thisWhen no callback is passed, the query is not executed.
You can use static methods :
userSchema.statics.findAll = function (cb) {
this.find(cb);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.