【问题标题】:How can I save this JSON to a mongoDB database serviced by MonogDB Compass?如何将此 JSON 保存到由 MongoDB Compass 提供服务的 mongoDB 数据库中?
【发布时间】:2018-12-24 04:52:58
【问题描述】:

我有一些原始 JSON 已填充用于测试目的,但现在我想使用 mongoDB Compass 将其放入 mongoDB 数据库中。

我的 mongoDB 连接字符串正在运行,并且我的 mongoose 代码正在运行。

我该怎么做?

我希望这将是一项简单的任务,因为 mongoDB 已经以 BSON 的形式存储它的数据。

这是我的代码的 sn-p。

const json_string = 
`[
  {
    "link":    "https://www.youtube.com/watch?v=BMOjVYgYaG8",
    "image":   "https://i.imgur.com/Z0yVBpO.png",
    "title":   "Debunking the paelo diet with Christina Warinner",
    // ... snip
  },
  { // ... snip

架构已创建:

// for relevant data from google profile
schema.Article = new Schema({ 
  link:       { type: String, required: true  },
  image:      { type: String, required: true  },
  title:      { type: String, required: true  },
  summary:    { type: String, required: true  },
  tag:        { type: String, required: true  },
  domain:     { type: String, required: true  }, 
  date:       { type: String, required: true  },   
  timestamp:  { type: Date, default: Date.now }
});

【问题讨论】:

  • MongoDB 不将其数据存储在 JSON 中!它存储结构化数据,是的,但是 JSON 是这种结构的字符串表示形式……而且您的数据库绝对不是(或不应该是)一堆字符串。
  • 显然是BSON,类似...en.wikipedia.org/wiki/BSON...更新

标签: javascript json mongodb mongoose bson


【解决方案1】:

你可以用这个

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
mongoose.connect(process.env.MONGO_URI);

const articleSchema = new Schema({
  link: { type: String, required: true },
  image: { type: String, required: true },
  title: { type: String, required: true },
  summary: { type: String, required: true },
  tag: { type: String, required: true },
  domain: { type: String, required: true },
  date: { type: String, required: true },
  timestamp: { type: Date, default: Date.now }
});

const Article = mongoose.model("Article", articleSchema);

const json_string = `[
  {
    "link":    "https://www.youtube.com/watch?v=BMOjVYgYaG8",
    "image":   "https://i.imgur.com/Z0yVBpO.png",
    "title":   "Debunking the paelo diet with Christina Warinner"
  }
]`;
const jsonBody = JSON.parse(json_string);

for (let i = 0; i < jsonBody.length; i++) {
  const data = jsonBody[i];
  const article = new Article({
    link: data.link,
    image: data.image,
    title: data.title
    //.... rest
  });
  article.save();
}
  1. 将 JSON 字符串转换为数组
  2. 遍历数组中的每个对象
  3. 根据对象中的值创建一个新的 Article 实例
  4. 在 Article 对象上调用 save 方法

【讨论】:

  • 在我的语法中,我使用的是 new Schema ({ ... // someSchema }) ,很好奇其中的区别,有参考吗?
  • @chris 编辑的答案,你所说的“有参考吗?”是什么意思??
  • 根据您的答案编辑...所以我认为这是一个错字,使用 new Schema() 是正确的方法吗?
  • 没有明确的正确答案,因为这两种方法都被接受且正确!
  • 你能参考一下Mongoose的这些信息吗...我正在寻找它。
猜你喜欢
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多