node.js - 以编程方式在 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"
}
}]
解决方案
使用它或创建 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();
推荐阅读
- visual-studio-code - 在 VSCode 中打开链接将在与 VSCode 相同的图标下创建一个新的 Web 浏览器
- java - wordpress 的所有 *.mp3 下载页面
- ruby-on-rails - 如何控制 Rails 中关系的非固定基数?
- java - 单击通知时如何将活动显示为弹出意图?
- c++ - 具有类型限定符的对象与成员函数不兼容
- discord.js - 如何将缩略图添加到 Discord 嵌入?
- time-complexity - 大哦!在 O(4^N) 中运行的算法
- visual-studio-2019 - .NET Core 3.1 在 VS2019 v16.6 中作为目标框架不可用
- java - OAuth 2.0 客户端 ID 和秘密 Java 实现
- python - 是否可以使用 python 将字段焦点设置为模糊或焦点在可填写的 PDF 文件表单字段中?