У меня есть проблема с извлечением данных.Извлечение данных 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
значение.
Конечно, вы получите 'undefined', как вы пытаетесь присвоить значение асинхронной' функции getAuthor' синхронно. – zaynetro