mongodb - 将字符串数组存储到 mongoDB 集合中
问题描述
我很陌生MongoDB
,mongoose
我有一个名为的模型名称agent
代理模型.js
const mongoose = require('mongoose')
const agentSchema = new mongoose.Schema({
agent: {
type: String,
required: true
}
})
const Agent = mongoose.model('Agent', agentSchema)
module.exports = Agent;
现在我有一个字符串数组:
const agentName = ['john', 'alex', 'david'];
现在我想将此数组作为单独的代理存储到 mongoDB 中。
像这样:
[
{
"_id": "6000977d9b94f52960955066",
"agent": "john",
"__v": 0
},
{
"_id": "6000977d9b94f52960955067",
"agent": "alex",
"__v": 0
},
{
"_id": "6000977d9b94f52960955068",
"agent": "david",
"__v": 0
}
]
注意:现在首先我使用这样的循环将我的字符串数组转换为对象数组:
agentName = agentName.map((e) => {return {agent: e}})
//以上代码行的输出
[ { agent: 'Alex Watson' },
{ agent: 'John Snow' },
{ agent: 'Rita Ora' } ]
然后我保存agentName。
但我正在寻找一些更好的方法,比如不需要将字符串数组转换为对象数组。
解决方案
您必须使用insertMany()
函数用于将多个文档插入到集合中。它接受一个array of documents
插入到集合中。像下面的代码一样,所以必须创建一个你创建的 abjects 数组
注意:在您的问题中定义const agentName
下一步将映射的结果分配给常量变量,所以这是错误的
const agentName = ['john', 'alex', 'david'];
let arr = agentName.map((e) => {return {agent: e}})
Agent.insertMany(arr).then(function(){
console.log("Data inserted") // Success
}).catch(function(error){
console.log(error) // Failure
});
推荐阅读
- windows - 添加客户端证书后,使用 Python 和 Postman 在 Windows 上“无法获取本地颁发者证书”
- php - 使用 Bootstrap 显示来自 DB 的结果
- go - gorm 使用 find 重新运行为空
- javascript - 以编程方式查找 chrome 中可用的最大可用缓存存储空间
- android - 应用程序设置允许通过移动网络下载?
- mysql - 将谷歌云存储连接到 mysql
- javascript - 添加和删除 VueJS 表单输入
- excel - 调试 Visual Basic 宏
- python - 如何在 python docx 中定位表格?
- python - 使用多处理池进行超参数调整