我试图用mlab发出一个find()请求。我在我的主文件(Controller)中使用express将它路由到我的模型中的函数,并在那里从DB执行find()。当应用程序输入此功能时,它可能仍然没有连接到数据库,因此conn.once中的代码不会运行。
所以我在方法中移动了mongooe.connect,现在客户端得到了一个空答案。我认为控制者在找到之前回答了答案。
//index.js (the controller)
const express = require('express');
app = express(),
data = require('./data/securitySettingsDB.json'),
port = process.env.PORT || 3000,
bodyParser = require('body-parser'),
methods = require('./modules');
var method = methods();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true }));
app.use(express.static('public'));
app.get('/', (req,res) => {
console.log('Trace: API Page');
res.sendFile(__dirname + '/api/index.html');
});
app.get('/getAllUsers/', (req, res) => {
res.setHeader('Debug', 'getAllUsers was reached');
res.status(200).json(method.getAllUsers());
});
app.listen(port);
console.log('listening on port ${port}');
//模块
const consts = require('../models/consts'),
mongoose = require('mongoose');
var User = require('../models/user');
class Methods {
getAllUsers() {
console.log("Trace : getAllUsers()");
mongoose.connect(consts.MLAB_KEY);
conn.on('error', (err) => {
console.log(`connection error: ${err}`);
});
conn.once('open', () => {
console.log(`once`);
User.find({}, (err, user) => {
if(err){
console.log(`query error ${err}`);
mongoose.disconnect();
return {"error": err}
}
else console.log(`ok`);
console.log(user);
mongoose.disconnect();
return user;
});
});
console.log(`returned from query`);
}
module.exports = function() {
var methods = new Methods();
return methods;
}
模型
var mongoose = require('mongoose'),
schema = mongoose.Schema,
userSchema = new schema({
user_name: {type:String, index:1, required:true, unique:true},
password: {type:String, required:true},
email: {type:String, required:true},
first_name: {type:String, required:true},
last_name: {type:String, required:true},
settings: {
login_alerts: {type:Boolean, required:true},
recognized_devices: [String]
},
phone_to_aproove_password_change: String
});
var User = mongoose.model('User', userSchema);
module.exports = User;
答案 0 :(得分:0)
Node.js是异步的。你需要做一些修复:
getAllUsers(clb) {
console.log("Trace : getAllUsers()");
mongoose.connect(consts.MLAB_KEY);
conn.on('error', (err) => {
console.log(`connection error: ${err}`);
});
conn.once('open', () => {
console.log(`once`);
User.find({}, (err, user) => {
if(err){
console.log(`query error ${err}`);
mongoose.disconnect();
return clb({"error": err});
}
else console.log(`ok`);
console.log(user);
mongoose.disconnect();
clb(null, user);
});
并像这样使用
app.get('/getAllUsers/', (req, res) => {
method.getAllUsers(function(err, users){
if(err){
throw err;
}
res.setHeader('Debug', 'getAllUsers was reached');
res.status(200).json(users);
});
})
});