简体   繁体   English

流星获得第一个集合的价值,找到另一个集合的价值

[英]Meteor get value of the first collection, to find value of the other collection

So I got two collections: 所以我得到了两个收藏:

  1. Users , with userId, firstname, surname. 具有userId,名字,姓氏的Users
  2. Answers , with answerId, questionId, and user. 具有answerId,questionId和user的Answers

The 'user' field in the 'Answers' collection, refers to the userId of the user who answerred the question. “答案”集合中的“用户”字段是指回答问题的用户的userId。

I am able to return the userId from the answers collection, but now I want to use the userId to find the Firstname en surname from the Users collection. 我能够从Answers集合中返回userId,但是现在我想使用userId从Users集合中查找Firstname姓。

Another solution could be to not insert the userId to the Answers collection, but the firstname and surname. 另一个解决方案可能是不将userId插入Answers集合中,而是插入名字和姓氏。 But I also dont know how to achieve this. 但我也不知道如何实现这一目标。

I hope you understand my question and I hope that anyone can help me! 希望您能理解我的问题,也希望任何人都能帮助我!

Yours, L 你的,L

You should be able to loop through each answer document in the Answers collection using the forEach() method, find the relevant user document by searching the Users collection for the id, as in the following example: 您应该能够使用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();
    }); 
}

The data will be reactive since when you use Deps.autorun, the entire block in function() {...} , will re-run every time a reactive variable, or document changes, in any way at all (that is updated, removed or inserted), or any other reactive variable change. 数据将是反应性的,因为当您使用Deps.autorun时, function() {...}的整个块将在反应性变量或文档完全以任何方式更改(即更新,删除或插入)或其他任何反应式变量更改。

As for the other solution where you update the userId in the Answers collection with the actual user document which has the firstname and surname, you can achieve this by way of using the Bulk API operations to do the updates. 至于其他解决方案,其中使用具有名字和姓氏的实际用户文档更新Answers集合中的userId ,则可以通过使用Bulk API操作进行更新来实现此目的。 You can get raw access to the collection and database objects in the npm MongoDB driver through rawCollection() and rawDatabase() methods on Mongo.Collection . 你可以通过原料进入在故宫的MongoDB驱动程序收集和数据库对象rawCollection()rawDatabase()方法上Mongo.Collection

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

You can get the Firstname and surname fields from the Users collection with this query: 您可以使用以下查询从“用户”集合中获取“姓氏”和“姓氏”字段:

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

userId has to be the value of the user's id in the Answers collection. userId必须是Answers集合中用户ID的值。

I'm assuming this value is corresponding to _id in the Users collection. 我假设此值对应于Users集合中的_id。

Saving the Firstname and surname of the user in each answer would cause unnecessary data duplication. 在每个答案中保存用户的名字和姓氏将导致不必要的数据重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM