【问题标题】:Nodejs and Mongoose data fetchingNodejs 和 Mongoose 数据获取
【发布时间】:2015-06-06 16:32:08
【问题描述】:

我在获取数据时遇到了一些问题。

我有猫鼬计划。

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

和获取方法

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

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

【问题讨论】:

  • 当然你会得到undefined,因为你正在尝试同步分配异步getAuthor函数的值。

标签: javascript node.js mongodb express mongoose


【解决方案1】:

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

但是您正在尝试做的事情已经内置到猫鼬中,它称为查询人口。

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

您可以配置一个 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);
    });

【讨论】:

    猜你喜欢
    • 2014-08-12
    • 2016-04-25
    • 2019-07-17
    • 1970-01-01
    • 2018-05-07
    • 2020-08-24
    • 2018-01-19
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多