我通过Mongoose使用Nodejs,ExpressJs,MongoDB . 我创建了一个简单的UserSchema . 我将我的代码分成多个文件,因为我预见它们会变得复杂 .
url'/ api / users'配置为调用'routes / user.js'中的list函数,该函数按预期发生 . UserSchema的列表函数确实被调用,但它无法向调用函数返回任何内容,因此没有结果 .
我究竟做错了什么 ?
我认为我在使用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;
routes/user.js
exports.list = function (req, res) {
UserModel.list(function (users) {
// this code never gets executed
console.log("Yay ");
return res.json(users);
});
}
1 回答
实际上在你的代码中你传递的是一个回调,它永远不会在函数中处理
userSchema.statics.list
您可以尝试以下代码:
因此,您应该更改传递给此函数的回调 . 即