Javascript Nodejs和Mongoose数据获取

Javascript Nodejs和Mongoose数据获取,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我在获取数据方面有一些问题 我有猫鼬计划 PostSchema.methods.getAuthor=function(){ this.model('User').findById(this.author).exec(函数(err,author){ 如果(作者){ console.log(author.username); 返回author.username; }; }); }; mongoose.model('Post',PostSchema); 和获取方法 exports.getPost=函

我在获取数据方面有一些问题

我有猫鼬计划

PostSchema.methods.getAuthor=function(){
this.model('User').findById(this.author).exec(函数(err,author){
如果(作者){
console.log(author.username);
返回author.username;
};
});
};
mongoose.model('Post',PostSchema);
和获取方法

exports.getPost=函数(req,res){
返回Post.findById(req.params.id,函数(err,Post){
如果(!post){
res.statusCode=404;
返回res.send({error:'notfound'});
}
如果(!err){
var author=post.getAuthor();
log('author is:',author);
返回res.send({status:'OK',post:post});
}否则{
res.statusCode=500;
返回res.send({error:'Server error'});
}
});
};

当我调用
post.getAuthor()
inside
getPost
方法时,他正在工作并通过Id找到用户。但是
var author=post.getAuthor()
未定义的
值。

正如@zaynetro提到的,您错误地调用了
getAuthor
方法。这是一个异步方法,所以您应该接受一个回调参数,或者您可以返回一个承诺

但您所要做的已经内置在mongoose中,它被称为查询填充

您可以配置Post.author引用属性,以便将mongoose解析到文档中

var postSchema = Schema({
    author: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    }
});
mongoose.model('Post', postSchema);

var userSchma = Schema({
    name: String
});
mongoose.model('User', userSchema);
然后,在您的路线中,您的查询将如下所示:

Post
    .findById(req.params.id)
    .populate('author')
    .exec(function(err, post) {
        if (err) {
            return res.status(500).send({
                error: 'Server error'
            });
        }
        // post.author contains the content of your author document
        return res.send(post);
    });

当然,当您试图同步地分配异步
getAuthor
函数的值时,会得到
undefined