【问题标题】:Pushing JSON with internal relational data to MongoDB?将带有内部关系数据的 JSON 推送到 MongoDB?
【发布时间】:2021-02-13 02:28:12
【问题描述】:

我有一个 JSON 想要放入我的 mongo db 数据库中。我的 JSON 包含一些关系数据。此数据是该 JSON 的内部数据,我不需要将其存储在其他任何地方。示例:

{
 title: "John film list"
 films [
   {
    title: "Once upon a time in Hollywood"
    director: '1a' //referencing the director using an ID of type string
   },
   {
    title: "Some film with empty director field",
    director: ''
   }
 ],
 directors: [
  {
    id: '1a', //find the director here
    name: 'Tarantino'
  }
 ]
}

我不需要集中存储任何东西(我不需要某个地方的大量导演列表),但是在这个文档中,我需要能够查找导演 (1a) 并找回 Tarantino。

我设法将这种 JSON 格式推送到 MongoDB。但是,它为我的模式提供了新的 id (_id-field),我现在对如何在 mongo 中正确关联这两者感到困惑?

【问题讨论】:

    标签: node.js json mongodb database-design mongoose-schema


    【解决方案1】:

    MongoDB 文档中默认的唯一主键是_id。当您插入一个新文档时,它会返回插入(创建)的记录的唯一 ID。

    这个id里面的值是根据时间创建的ObjectId。你可以阅读它here

    如果你想为 _id 使用自己的值,必须在调用插入时传递它,如下所示:

    db.directors.insertOne({_id: '1a', name: 'Tarantino'})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-12
      • 2018-07-07
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多