【问题标题】:How to populate an object inside an object in an array?如何在数组中的对象内填充对象?
【发布时间】:2020-10-25 03:51:08
【问题描述】:

我目前正在使用 mongoose 进行一个项目,但我遇到了 mongoose populate() 方法的问题。

问题是我无法在数组中的对象内填充对象。

// * I simplified the code below.

// Profile Document
Profile = model('Profile', new Schema({
    _user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
    },
    posts: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Post',
        // Post = { 
        //   _id: Number,
        //   _poster: { 
        //     type: Schema.Types.ObjectId,
        //     ref: 'User',
        //   }
        // };
      },
    ],
}));

// app.js
 const profile = await Profile.findOne({ _user: userId })
    .populate('_user')  // it works
    .populate('posts')  // it works too
    .populate('posts._poster'); // it doesn't work

有没有办法在数组中填充嵌套对象?

如果你能回答我的问题,那就太好了。提前谢谢你。



我尝试正确访问符号以填充 *_poster*,但是它仍然无法正常工作。代码如下。

    const profile = await Profile.findOne({ _user: userId })
      .populate('_user')
      .populate('posts');

    await profile.toObject();
    profile.posts.forEach((post) => {
      profile.populate('posts.post._poster');
    })

【问题讨论】:

  • 您的_poster 在您的数据结构中被注释掉了。此外,如果posts 是一个数组,我没有看到您指定索引来访问数组的元素。为什么点符号在这种情况下会起作用?
  • 我注释掉只是为了澄清模型内部,很抱歉让您感到困惑。在获取对象 JavaScript 对象后,我尝试访问该符号,但是,它不能用作 JavaScript 对象并且无法填充。

标签: node.js mongoose mongoose-populate


【解决方案1】:

我已经测试了你的架构,效果很好,你能测试一下并告诉我

const profile = await Profile.findOne({
        _id: '5f108ed7ecc4881a6c35e27b',
    })
        .populate('_user')
        .populate({
            path: 'posts',
            populate: {
                path: '_poster',
                model: 'User',
            },
        })
        .exec();
    console.log(profile);

【讨论】:

  • 超级!!我已经测试了你的代码,效果很好。非常感谢。
  • 点赞并将其标记为正确答案,这样也可以帮助其他人
猜你喜欢
  • 2018-11-14
  • 1970-01-01
  • 2013-03-10
  • 2020-10-13
  • 2013-06-30
  • 2022-01-24
  • 2016-01-19
  • 2022-08-02
  • 2023-03-16
相关资源
最近更新 更多