这里是代码:
var mongoos = require('./getMongoos.js');
var user = mongoos.addressFromMongoos(username[0]);
console.log(user); // i need the mongoos find here
getMongoos.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userShema = new Schema({
username: String
});
db = mongoose.createConnection('localhost/***');
var user = db.model('User', userShema);
exports.addressFromMongoos = function(username){
user.find({username: username}, function(err, user) {
if (err) {
callback(err, null);
} else {
console.log(user); //works
}
});
};
但我不知道如何在var用户中返回查找用户:
var user = mongoos.addressFromMongoos(username [0]);
答案 0 :(得分:1)
您无法直接从同步函数返回异步结果。你必须改为使用回调:
exports.addressFromMongoos = function(username, callback){
user.findOne({username: username}, callback);
};
将其称为:
mongoos.addressFromMongoos(username[0], function(err, user) {
console.log(user);
});