【问题标题】:Posting to mongoDb with ObjectId Many to one relationship使用 ObjectId 发布到 mongoDb 多对一关系
【发布时间】:2020-07-13 16:53:51
【问题描述】:

Mongoose/MongoDB 问题

我有一个包含基本配置文件数据的 Owners 模型。

我有一个二级模型:OwnersImages 例如

    {
        owner: { 
            type: Schema.Types.ObjectId,
            ref: 'Owners'
        },
        name: String,
        imageUrl: String,
    },
);

我想从客户端将 imageUrl 和名称发布到 OwnersImages 表。 例如

          let values = {
            owner: this.state.user._id,
            name: this.state.field,
            imageUrl: this.state.url
          }
          axios.post(`${serverPath}/api/addFieldImage`, values)

但是我不确定如何最好地解决这个问题,链接它等等。

我可以对 Owners 表执行 GET 请求以获取 Owner 数据,但随后将其作为值的一部分发布到 OwnerImages 不会成功链接两个表。

我只需要在OwnerImages 中存储对所有者 ID 的字符串引用还是有更聪明的方法?

或者我应该将用户 ID 的字符串发布到 mongoose,然后从那里映射到 Owner 表?

我试图以最好的方式解释这个,但眼睛很累,所以请询问是否有任何困惑! 非常感谢

【问题讨论】:

  • 您是否尝试查看$lookup 一个聚合运算符JOINS 两个集合?
  • 你能更好地解释一下OwnerImages是什么吗?这是另一个模式吗? OwnerImagesOwners 有什么区别?
  • Owners 是用户模型,OwnerImages 是链接到所有者的上传图片模型

标签: reactjs mongodb mongoose axios


【解决方案1】:

没有看到您的确切设置,我认为您可以修改它以满足您的需求:

// In the Schema/Model files
const ownersSchema = Schema({
  // other fields above...
  images: [{ type: Schema.Types.ObjectId, ref: 'OwnersImages' }]
});

const ownersImagesSchema = Schema({
  // other fields above...
  owner: { type: Schema.Types.ObjectId, ref: 'Owners' },
});


// in the route-handler
Owners.findById(req.body.owner, async (err, owner) => {
  const ownersImage = new OwnersImages(req.body);
  owner.images.push(ownersImage._id);
  await ownersImage.save();
  await owner.save();
});

作为旁注,我认为模型通常具有单数名称,例如 Owner 和 OwnerImage。然后该集合将自动采用复数形式。值得深思。

当你想加载这些时,你可以用populate()链接它们。考虑在某个路由处理程序中加载与Owners 关联的所有OwnersImages,其中/:id 参数是Owners id:

Owners
  .findOne({ _id: req.params.id })
  .populate('images')
  .exec(function (err, images) {
    if (err) return handleError(err);
    // do something with the images...
  });

【讨论】:

  • 谢谢丹尼尔,这很有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
相关资源
最近更新 更多