3

Mongoose経由でNodejs、ExpressJs、MongoDBを使用しています。シンプルな UserSchema を作成しました。コードが複雑になることが予想されるため、コードを複数のファイルに分割しています。

URL '/api/users' は、'routes/user.js' で list 関数を呼び出すように構成されており、これは期待どおりに行われます。UserSchema のリスト関数は呼び出されますが、呼び出し元の関数に何も返さないため、結果は出ません。

私は何を間違っていますか?

http://pixelhandler.com/blog/2012/02/09/develop-a-restful-api-using-node-js-with-express-and-mongoose/に基づいてモデル化しようとしました

userSchema.statics.list の関数定義に何か問題があると思います

app.js

users_module = require('./custom_modules/users.js'); // I have separated the actual DB code into another file
mongoose.connect('mongodb:// ******************');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
    users_module.init_users();
});

app.get('/api/users', user.list);

custom_modules/users.js

function init_users() {
    userSchema = mongoose.Schema({
        usernamename: String,
        hash: String,
    });

    userSchema.statics.list = function () {
        this.find(function (err, users) {
            if (!err) {
                console.log("Got some data"); // this gets printed 

                return users; // the result remains the same if I replace this with return "hello" 
            } else {
                return console.log(err);
            }
        });
    }

    UserModel = mongoose.model('User', userSchema);
} // end of init_users

exports.init_users = init_users;

ルート/user.js

exports.list = function (req, res) {
    UserModel.list(function (users) {
        // this code never gets executed
        console.log("Yay ");

        return res.json(users);
    });
}
4

1 に答える 1

1

実際にあなたのコードでは、コールバックを渡していますが、これは関数で処理されることはありませんuserSchema.statics.list

次のコードを試すことができます。

userSchema.statics.list = function (calbck) {    
  this.find(function (err, users) {
    if (!err) {        
      calbck(null, users); // this is firing the call back and first parameter should be always error object (according to guidelines). Here no error, so pass null (we can't skip)
    } else {    
         return calbck(err, null); //here no result. But error object. (Here second parameter is optional if skipped by default it will be undefined in callback function)
      }
    });    
 }

したがって、この関数に渡されるコールバックを変更する必要があります。すなわち

exports.list = function (req, res){
UserModel.list(function(err, users) {
   if(err) {return console.log(err);}
   return res.json(users);
  });
} 
于 2013-08-21T06:58:55.403 に答える