1

I created some mocked data in database and export it as json so i can use it for seed, after drop the database. How to import .json file in mongodb programatically This is json file:

[{
  "_id": {
    "$oid": "5fdb7f818079290de4fffa5a"
  },
  "twoFactorAuthenticationEnabled": false,
  "email": "[email protected]",
  "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": "[email protected]",
  "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"
  }
}]
1
  • 1
    what do you mean with programatically? you need to use mongoimport, that's all Commented Dec 17, 2020 at 19:03

1 Answer 1

1

Use this or create Schema and use it like this:

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)

Without mongoose:

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Is there any mongodb example for creating a schema since i'm not using mongoose

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.