【问题标题】:How do i pass in the object id in a collection as a property in another collection in mongodb如何将集合中的对象ID作为mongodb中另一个集合中的属性传递
【发布时间】:2020-05-26 12:18:11
【问题描述】:

我已经使用 nodejs、express 和 ejs 构建了一个博客,其中包含用于身份验证的登录和注册设置。我只想让用户能够保护他们的帖子,即只允许他们能够编辑和删除他们的帖子。使用 mongodb 找到一种方法非常令人沮丧,因为我在网上搜索时还没有找到明确的方法。

我看到一个可能有解决方案的 youtube 视频:


module.exports = {
    ROLE: ROLE,
    users: [
        { id: 1, name: 'Kyle', role: ROLE.ADMIN },
        { id: 2, name: 'Sally', role: ROLE.BASIC },
        { id: 3, name: 'Joe', role: ROLE.BASIC }

    ],
    projects: [
        { id: 1, name: "Kyle's project", userId: 1 },
        { id: 2, name: "Sally's Project", userId: 2 },
        { id: 3, name: "Joe's project", userId: 3 }
    ]
}

他的逻辑是基于将 users 集合的 id 属性与 projects 集合的 userId 属性进行匹配,这意味着 userId 必须与 users 集合中的 id 属性相同。

有没有一种方法可以在我的博客模型中将属性设置为名为 userid 的属性,使其等于我登录用户的 id 的 id。

【问题讨论】:

    标签: node.js database mongodb authentication passport.js


    【解决方案1】:

    我会尝试使用 mongoose 中的填充方法。创建用户和帖子模式,然后通过添加一个属性来链接它们,该属性将帖子所有者与适当的用户联系起来。 看看文档!
    mongoose docs populate

    【讨论】:

      猜你喜欢
      • 2019-10-01
      • 1970-01-01
      • 2014-01-08
      • 2021-11-08
      • 1970-01-01
      • 2012-08-26
      • 2020-12-25
      • 1970-01-01
      • 2012-01-08
      相关资源
      最近更新 更多