質問

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.

From the docs:

Query#find([criteria], [callback])

Finds documents.

Parameters:

[criteria] <Object> mongodb selector
[callback] <Function>

Returns:

<Query> this

When no callback is passed, the query is not executed.


Recommended solution

You can use static methods:

userSchema.statics.findAll = function (cb) {
  this.find(cb);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top