Reputation: 45
I have some problem with data fetching.
I have mongoose scheme.
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);
and 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' });
}
});
};
When I call post.getAuthor()
inside getPost
method he is work and found User by Id. But var author = post.getAuthor();
have undefined
value.
Upvotes: 3
Views: 141
Reputation: 8151
As @zaynetro mentioned you're calling your getAuthor
method incorrectly. It's an asynchronous method, so you should be accepting a callback parameter, or you could return a promise.
But what you're trying to do is already built in to mongoose, its called query population.
http://mongoosejs.com/docs/populate.html
You can configure a Post.author reference property that you can have mongoose resolve into the document for you.
var postSchema = Schema({
author: {
type: Schema.Types.ObjectId,
ref: 'User'
}
});
mongoose.model('Post', postSchema);
var userSchma = Schema({
name: String
});
mongoose.model('User', userSchema);
Then, in your route your query would look like this:
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);
});
Upvotes: 3