Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Users = [{
- _id: 1,
- name: "Sam",
- email: "sam@gmail.com",
- group: "Rangers"
- },
- {
- _id: 2,
- name: "Michael",
- email: "michael@gmail.com"
- group: "Muse"
- },
- {
- _id: 3,
- name: "John",
- email: "john@gmail.com"
- group: "Merchant"
- },
- .....
- ]
- Items = [
- {
- _id: 1,
- user_id: 1,
- item_name: "Flying Sword",
- timestamp: ...
- },
- {
- _id: 3,
- user_id: 1,
- item_name: "Invisible Cloak",
- timestamp: ...
- },
- {
- _id: 4,
- user_id: 2,
- item_name: "Iron Shield"
- },
- {
- _id: 5,
- user_id: 7,
- item_name: "Splashing Gun",
- timestamp: ...
- },
- ...
- ]
- Users.find({group: "Muse"}, function(err, users){
- I DON"T KNOW WHAT TO WRITE INSIDE
- })
- [
- {
- _id: 4,
- name: "Jack",
- email: "jack@gmail.com",
- group: "Muse",
- items: [
- {
- _id: 8
- name: "Magic Wand",
- user_id: 4,
- timestamp: ...
- }
- {
- _id: 12
- name: "Blue Potion",
- user_id: 4,
- timestamp: ...
- },
- {
- _id: 18
- name: "Teleportation Scroll",
- user_id: 4,
- timestamp: ...
- }
- ]
- }
- .....
- More USERS of similar structure
- ]
- Users.find({group: "Muse"}, function(err, users){
- var userIDs;
- if (err) {
- // do error handling
- return;
- }
- userIDs = users.map(function (user) { return user._id; });
- Items.find({user_id: {$in: userIDs}}, function (err, items) {
- if (err) {
- // do error handling
- return;
- }
- users.forEach(function (user) {
- user.items = items.filter(function (item) {
- return item.user_id === user._id;
- });
- });
- // do something with modified users object
- });
- });
- Users.find({group: "Muse"}).exec().then(function(users) {
- var userIDs = users.map(function(user) {
- return user._id;
- });
- // returns a promise
- return Promise.all([
- // include users for the next `then`
- // avoids having to store it outside the scope of the handlers
- users,
- Items.find({
- user_id: {
- $in: userIDs
- }
- }).exec()
- ]);
- }).then(function(results) {
- var users = results[0];
- var items = results[1];
- users.forEach(function(user) {
- user.items = items.filter(function(item) {
- return item.user_id === user._id;
- });
- });
- return users;
- }).catch(function (err) {
- // do something with errors from either find
- });
- Users.find({group: "Muse"}).exec().then(function(users) {
- return bluebird.map(users, function(user) {
- return Items.find({user_id: user._id}).exec().then(function (items) {
- user.items = items;
- return user;
- });
- }, {concurrency: 5});
- }).then(function(users) {
- // do something with users
- }).catch(function(err) {
- // do something with errors from either find
- });
Add Comment
Please, Sign In to add comment