Mongoose我怎么能返回findOne数据对象

时间:2014-06-09 08:56:53

标签: node.js mongodb mongoose

这里是代码:

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

1 个答案:

答案 0 :(得分:1)

您无法直接从同步函数返回异步结果。你必须改为使用回调:

exports.addressFromMongoos = function(username, callback){
    user.findOne({username: username}, callback);
};

将其称为:

mongoos.addressFromMongoos(username[0], function(err, user) {
    console.log(user);
});