简体   繁体   中英

Populate values from different Models - Mongoose/MongoDB Collections - NodeJS

I have two main Schema in my project, Store, and User.

  • User collection as displayed in MongoDB Compass is the following :

     _id : ObjectId("**5e830006c4cec2586875124b**") hearts : Array storeID : Array email : "test@test.com" name : "My name is Test" photo : "fa75fa97-c5d8-4e63-a9ee-38441774a26e.jpeg" slugAuthor : "my-name-is-test" description : "My description is Test" hash : "b841b82dcffdd0d517b5010d9ff2047ab447751a4e6dd573f9d55af..." salt : "2bb0f785b134af11d7ca08d4086801fd880626498fbcf106c0df9a66" __v : 0
  • Store collection as displayed in MongoDB Compass is the following :

     _id : ObjectId("5e830050c4cec2586875124c") tags : Array name : "My activity is Test" description : "My description us Test" participants : 1 duree : 1 date : 2220-02-22T21:02:00.000+00:00 author : ObjectId("**5e830006c4cec2586875124b**") created : 2020-03-31T08:33:20.234+00:00 slug : "my-activity-is-test" __v : 0

What I need :

When I display the user information, I also want to search every Store he has created.
As you can see, the User id is found in the Store collection (author: ObjectId).

I need to display those information (User + list of stores that belongs to the User) when I hit the route http://..../store/my-name-is-test/5e830006c4cec2586875124b . In my route, I need to display as a slug the "slugAuthor" and the "author: ObjectId". (this is already managed).

What I have already tried (using .populate()) :

In my Store Schema :

author: {
        type: mongoose.Schema.ObjectId,
        ref: 'User', 
    }

In my User Schema :

listStores: [{
    type: mongoose.Schema.ObjectId,
    ref: 'Store'}], 

In my controller:

exports.myProfil = async (req, res) => {
        const user = await User.findOne({slugAuthor: req.params.slugAuthor}).populate('listStores') 
        res.render('my-profil', {user}); 
    };  

It gives me access to the following data :

{
  "hearts": [],
  "listStores": [],
  "_id": "5e830006c4cec2586875124b",
  "email": "test@test.com",
  "name": "My name is Test",
  "photo": "fa75fa97-c5d8-4e63-a9ee-38441774a26e.jpeg",
  "slugAuthor": "my-name-is-test",
  "description": "My description is Test",
  "__v": 0
}

As you can see, "listStores" array is empty but I need it to be filled with every stores created by this user.

Would you please be kind enough to help me out here,
Many thanks

You can use aggregation for that. Take a look at the lookup

   $lookup:
     {
       from: 'Store',
       localField: _id, // the _id of the user
       foreignField: author,
       as: "listStores" // this might be something else
     }

In this case instead of find you have to use User.aggregate

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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