Как сохранить этот JSON в базе данных mongoDB, обслуживаемой MonogDB Compass? - PullRequest
0 голосов
/ 23 декабря 2018

У меня есть какой-то необработанный JSON, который я заполнил для целей тестирования, но теперь я хотел бы поместить его в базу данных mongoDB с помощью mongoDB Compass.

Моя строка подключения 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 голосов
/ 23 декабря 2018

Вы можете использовать это

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. Создание нового экземпляра статьи на основедля значений из объекта
  4. Вызовите метод сохранения для объекта Article
...