node.js - MongoDB 填充性能

标签 node.js mongodb performance async.js mongoose-populate

最近问了这样一个问题。

Mongo 中哪个更快:填充或单独的异步请求?

示例

var mongoose = require('mongoose')
    , Schema = mongoose.Schema;

var FeedPostCommentSchema = new Schema({

    feedPost: {type: Schema.Types.ObjectId, ref: 'FeedPost', index: true},
    user: {type: Schema.Types.ObjectId, ref: 'User'},

    comment: {
        type: String,
        trim: true
    },

    updated: {type: Date, default: Date.now},
    created: {type: Date, default: Date.now, index: true}
});

mongoose.model('FeedPostComment', FeedPostCommentSchema);

展示所有评论的时候,我们还需要获取用户数据

我们可以将其设为标准填充方法:

FeedPostComment.find({feedPost: req.params.postId}).populate('user')
        .skip(skip)
        .limit(limit)
        .sort({created: -1})
        .lean()
        .exec()

我们还可以通过并行查询来做到这一点:

FeedPostComment.find({feedPost: req.params.postId})
        .skip(skip)
        .limit(limit)
        .sort({created: -1})
        .lean()
        .exec(function (err, comments) {
            async.each(comments, function (comment, cb) {
                User.findById(comment.user, function (err, composer) {
                    if (err) {
                        return cb(err);
                    }

                    comment.user = utils.getPublicDataOfUser(composer);
                    cb();
                });
            }, function (err) {
                comments.reverse();
            });
        });

最佳答案

填充总是比正常的异步请求更快...但现在甚至比已经引入的更快,即 $lookuppipeline...你可能应该选择它。

关于node.js - MongoDB 填充性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50332384/

相关文章:

node.js - 无法获取环境 key 来读取我的 Nodejs 程序

node.js - React错误找不到模块 './lib/api/node.js'

JavaScript 错误/不良实践

node.js - minimongo 是否存在于运行 Meteor 的服务器实例上?

swift - Vapor MongoDB 提供程序错误

python - 高效的数组连接

java - 我可以加快扫描端口进程吗?

node.js - 如何停止在 forEach 中附加字符串?

Node.js-无法将 Apple 推送通知发送到开发设备以进行调试

linux - Raspbian 上的 Mono 和 MongoDB