繁体   English   中英

填充来自不同模型的值 - Mongoose/MongoDB 集合 - NodeJS

[英]Populate values from different Models - Mongoose/MongoDB Collections - NodeJS

我的项目中有两个主要架构,Store 和 User。

  • MongoDB Compass显示的用户集合如下:

     _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
  • MongoDB Compass显示的存储集合如下:

     _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

我需要什么

当我显示用户信息时,我还想搜索他创建的每个Store。
如您所见,用户 ID 位于 Store 集合中(author: ObjectId).

当我点击路由http://..../store/my-name-is-test/5e830006c4cec2586875124b时,我需要显示这些信息(用户 + 属于用户的商店列表)。 在我的路线中,我需要将“slugAuthor”和“作者:ObjectId”显示为slug。 (这已经被管理了)。

我已经尝试过(使用 .populate()):

在我的商店架构中:

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

在我的用户架构中:

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

在我的控制器中:

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

它使我可以访问以下数据:

{
  "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
}

如您所见,“listStores”数组是空的,但我需要用该用户创建的每个商店填充它。

你能不能帮我一下,
非常感谢

您可以为此使用聚合。 看一下查找

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

在这种情况下,您必须使用 User.aggregate 而不是 find

希望这可以帮助!

暂无
暂无

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

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