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);
});
}