如何将该JSON保存到MonogDB Compass服务的mongoDB数据库?

时间:2018-12-23 19:46:17

标签: javascript json mongodb mongoose bson

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

我的mongoDB连接字符串正常工作,并且我的Mongoose代码正常工作。

我该怎么做?

我希望这将是一件容易的事,因为mongoDB已经以BSON的形式存储了数据。

这是我的代码的片段。

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 }
});

1 个答案:

答案 0 :(得分:2)

您可以使用此

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方法