我对MongoDB和mongoose非常陌生,我有一个模型名叫agent
agent.model.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。
,但我正在寻找一些更好的方法,比如不需要将字符串数组转换为对象数组.。
发布于 2021-01-14 23:09:20
必须使用insertMany()函数向集合中插入多个文档。它接受要插入到集合中的array of documents。就像下面的代码一样,所以必须创建一个下注数组,这是您创建的
注意:在您的问题中定义了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
}); https://stackoverflow.com/questions/65725643
复制相似问题