【问题标题】:Meteor get value of the first collection, to find value of the other collectionMeteor 获取第一个集合的值,查找另一个集合的值
【发布时间】:2016-01-25 08:51:37
【问题描述】:

所以我得到了两个集合:

  1. 用户,包括用户 ID、名字、姓氏。
  2. 答案,带有 answerId、questionId 和 user。

'Answers'集合中的'user'字段,是指回答问题的用户的userId。

我可以从 answers 集合中返回 userId,但现在我想使用 userId 从 Users 集合中查找 Firstname en surname。

另一种解决方案可能是不将 userId 插入 Answers 集合,而是将名字和姓氏插入。但我也不知道如何实现这一点。

希望你能理解我的问题,希望任何人都可以帮助我!

你的, 升

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    您应该能够使用 forEach() 方法遍历 Answers 集合中的每个答案文档,通过在 Users 集合中搜索 id 来找到相关的用户文档,如在以下示例中:

    Answers = new Meteor.Collection("answers");
    Users = new Meteor.Collection("users");
    
    if(Meteor.isClient) {
        processed_data = []; 
    
        Deps.autorun(function (c) {
            console.log('run');
            var cursor = Answers.find({}, { sort: { time: 1 }});
            if (!cursor.count()) return;
    
            cursor.forEach(function (ans) {
                var user = Users.findOne({ "_id": ans.user }, { "fields": {"firstname": 1, "surname": 1} });
                ans.user = user;
                processed_data.push(ans);
            }); 
    
            console.log(processed_data);
            c.stop();
        }); 
    }
    

    数据将是响应式的,因为当您使用 Deps.autorun 时,function() {...} 中的整个块将在每次响应式变量或文档以任何方式发生变化时重新运行(即更新、删除或插入),或任何其他反应性变量更改。

    至于使用具有名字和姓氏的实际用户文档更新Answers集合中的userId的其他解决方案,您可以通过使用Bulk API operations 进行更新。您可以通过 Mongo.Collection 上的 rawCollection()rawDatabase() 方法获取对 npm MongoDB 驱动程序中的集合和数据库对象的原始访问权限.

    Answers = new Meteor.Collection("answers");
    Users = new Meteor.Collection("users");
    
    if (Meteor.isClient) {
        Template.answerlist.helpers({
            answers: function () {
                processed_data = []; 
    
                Deps.autorun(function (c) {
                    console.log('run');
                    var cursor = Answers.find({}, { sort: { time: 1 }});
                    if (!cursor.count()) return;
    
                    cursor.forEach(function (ans) {
                        var user = Users.findOne({ "_id": ans.user }, { "fields": {"firstname": 1, "surname": 1} });
                        ans.user = user;
                        processed_data.push(ans);
                    }); 
    
                    console.log(processed_data);
                    c.stop();
                }); 
    
                return processed_data;
            }
        });
    
        Template.answerlist.events({
            'click #updateAnswers': function(ev) {
                Meteor.call('updateAnswersUser');
            }
        });
    
    }
    
    
    if (Meteor.isServer) {
        Meteor.startup(function () {
            Meteor.methods({
                updateAnswersUser: function() {
                    var bulkOp = Answers.rawCollection().initializeUnorderedBulkOp(),
                        counter = 0;
                    Answers.find({}).forEach(function(ans) {
                        var user = Users.findOne({ "_id": ans.user }, { "fields": {"firstname": 1, "surname": 1} });
                        var changes = {};
                        changes["user"] = user;
                        bulkOp.find({"_id": ans._id}).updateOne({ "$set": changes });
    
                        counter++;
                        if (counter % 1000 == 0) {
                            // Execute per 1000 operations and re-initialize every 1000 update statements
                            bulkOp.execute(function(e, r) {
                                console.info('r.nMatched', r.nMatched, 'r.nModified', r.nModified);
                            });
                            bulkOp = Answers.rawCollection().initializeUnorderedBulkOp();
                        }
                    }); 
    
                    // Clean up queues
                    if (counter % 1000 != 0){
                        bulkOp.execute(function(e, r) {
                            console.info('r.nMatched', r.nMatched, 'r.nModified', r.nModified);
                        });
                    }
                }
            }); 
        });
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用此查询从用户集合中获取名字和姓氏字段:

      Users.find({_id: userId}, {fields:{Firstname: 1, surname: 1}}).fetch();
      

      userId 必须是 Answers 集合中用户 id 的值。

      我假设这个值对应于用户集合中的 _id。

      在每个答案中保存用户的名字和姓氏会导致不必要的数据重复。

      【讨论】:

      • "在每个答案中保存用户的名字和姓氏会导致不必要的数据重复。"这就是 mongodb 的漏洞,创建包含所有信息的文档,这样您就不必在客户端加入数据。
      • 感谢您指出@Phoenix。复制在这里可能不是问题,实际上是一个很好的解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多