Getting Nodejs and Mongoose data

I have a problem retrieving data.

I have a diagram of a 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);

      

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 the method getPost

, it works and finds the user by id. But var author = post.getAuthor();

it matters undefined

.

+3


source to share


1 answer


As @zaynetro pointed out, you are calling your method incorrectly getAuthor

. This is an asynchronous method, so you must accept a callback parameter, or you can return a promise.

But what you are trying to do is already built into mongoose, its callable query scope.

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

You can customize the Post.author link property so that you can allow permission for mongoose in the document.



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

var userSchma = Schema({
    name: String
});
mongoose.model('User', userSchema);

      

Then on your route, your request will 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);
    });

      

+3


source







All Articles