2015-06-06 80 views
3

我有一些数据获取问题。Nodejs和Mongoose数据获取

我有猫鼬计划。

PostSchema.methods.getAuthor = function() { 
    this.model('User').findById(this.author).exec(function (err, author){ 
     if (author) { 
      console.log(author.username); 
      return author.username; 
     }; 
    }); 
}; 

mongoose.model('Post', PostSchema); 

和getMethod

exports.getPost = function (req, res) { 
    return Post.findById(req.params.id, function (err, post) { 
     if (!post) { 
      res.statusCode = 404; 
      return res.send({ error: 'Not found' }); 
     } 
     if (!err) { 
      var author = post.getAuthor(); 
      console.log('author is: ', author); 

      return res.send({ status: 'OK', post:post }); 
     } else { 
      res.statusCode = 500; 
      return res.send({ error: 'Server error' }); 
     } 
    }); 
}; 

当我打电话post.getAuthor()getPost方法,他的工作,并通过ID已找到用户。但var author = post.getAuthor();undefined值。

+1

当然你'undefined'与您试图同步异步分配'getAuthor'函数的值。 – zaynetro

回答

3

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

但是你想要做的是已经内置到猫鼬,其被称为查询人口。

http://mongoosejs.com/docs/populate.html

你可以配置你可以有猫鼬决心到你的文档Post.author引用属性。

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