我正在使用Node.js,Express,MongoDB和Mongoose。我有一个函数,它获取MongoDB数据库中文档的最大id号并将其返回给程序。我已经开始模块化我的代码,并已将该功能迁移到另一个模块。我已成功访问主模块中的函数,但它涉及异步数据库查询。当函数返回一个值时,我想将它分配给一个变量。不幸的是,当将返回值赋给变量时,该变量实际上设置为undefined。我正在考虑使用事件发射器来表示查询已完成,但这也提出了两个问题:
1)我不认为你可以在一个程序之后做一个返回声明,这是必需的。
2)模块之间的事件发射器看起来非常挑剔。
请帮我把变量分配给正确的值。主要功能和模块的代码如下:
(主文件)app.js:
//requires and start up app
var express = require('express');
var mongoose = require('mongoose')
, dbURI = 'localhost/test';
var app = express();
var postmodel = require('./models/post').postmodel;
//configures app for general stuff needed such as bodyParser and static file directory
app.configure(function () {
app.use(express.bodyParser());
app.use(express.static(__dirname + '/static'));
});
//configures app for production, connects to mongoLab databse rather than localhost
app.configure('production', function () {
dbURI = 'mongodb://brad.ross.35:lockirlornie@ds037387.mongolab.com:37387/heroku_app6901832';
});
//tries to connect to database.
mongoose.connect(dbURI);
//once connection to database is open, then rest of app runs
mongoose.connection.on('open', function () {
var PostModel = new postmodel();
var Post = PostModel.setupPostSchema();
var largest_id = PostModel.findLargestID(Post);
(模块)post.js:
var mongoose = require('mongoose');
module.exports.postmodel = function () {
this.setupPostSchema = function () {
var postSchema = new mongoose.Schema({
title: String,
body: String,
id: Number,
date_created: String
});
var Post = mongoose.model('Post', postSchema);
return Post;
};
this.findLargestID = function (Post) {
Post.find(function (err, posts) {
if (err) {
console.log("error finding largest ID!");
} else {
var largest_id = 0;
for (var post in posts) {
if (posts[post].id >= largest_id) largest_id = posts[post].id;
}
console.log(largest_id);
return largest_id;
}
});
};
};
答案 0 :(得分:3)
您需要findLargestID
接受一个largest_id
可用后将调用的回调参数:
this.findLargestID = function (Post, callback) {
Post.find(function (err, posts) {
if (err) {
console.log("error finding largest ID!");
callback(err);
} else {
var largest_id = 0;
for (var post in posts) {
if (posts[post].id >= largest_id) largest_id = posts[post].id;
}
console.log(largest_id);
callback(null, largest_id);
}
});
};