首页 > 解决方案 > 以编程方式在 mongodb 中插入 JSON 文件

问题描述

我在数据库中创建了一些模拟数据并将其导出为 json,以便在删除数据库后将其用作种子。如何以编程方式在 mongodb 中导入 .json 文件这是 json 文件:

[{
  "_id": {
    "$oid": "5fdb7f818079290de4fffa5a"
  },
  "twoFactorAuthenticationEnabled": false,
  "email": "user@abv.bg",
  "password": "$argon2i$v=19$m=4096,t=3,p=1$zAiJVpwejt30MP8bqOYObA$EfU+wLtFEIMaLRL+dZJRIZqQINNyFy82ptCFxK7RVRQ",
  "confirmed": true,
  "role": "user",
  "walletAddress": "0x8587431eaaDC8756288ef49651f00Dce55F67D7e",
  "privateKey": "0x18025dca0404d5ecffc2f7b2df2fb4c5619434a3810d75c6e8bf42035c9e5f8b",
  "createdAt": {
    "$date": "2020-12-17T15:55:45.989Z"
  }
},{
  "_id": {
    "$oid": "5fdb7f828079290de4fffa5b"
  },
  "twoFactorAuthenticationEnabled": false,
  "email": "superadmin@abv.bg",
  "password": "$argon2i$v=19$m=4096,t=3,p=1$H59MQO281W7T3I2nZLv5Qg$Ec9+5cnFJG0yhQqKtZHeNXSp8XjoQs8nnTHl40KPM6U",
  "confirmed": true,
  "role": "user",
  "walletAddress": "0xeE1A85afA7E9D391fC0f740dA45958195f89f053",
  "privateKey": "0x2edb234652d9761906bfd5d75005bab1c57e114ed84cf08134d35452f3b37363",
  "createdAt": {
    "$date": "2020-12-17T15:55:46.020Z"
  }
}]

标签: node.jsmongodb

解决方案


使用或创建 Schema 并像这样使用它:

const mongoose = require('mongoose');

mongoose.connect(myMongoUrl)
  .then(() => console.log('MongoDB connected'))
  .catch(error => console.log(error));

const myDataSchema = new Schema({
  twoFactorAuthenticationEnabled: {
    type: Boolean,
    default: false,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  ...
});

const myModel = mongoose.model('myData', myDataSchema);

myModel.insertMany(myArrayWithData)

没有猫鼬:

const { MongoClient } = require('mongodb');

const client = new MongoClient(myMongoUrl);

const DB = client.db(databasename);

const myAsyncFunction = async() => {

  const collection = await DB.collection(nameOfCollection); // or DB.createCollection(nameOfCollection);

  await collection.insertMany(myArrayWithData);
};

client.close();

推荐阅读