首页 > 解决方案 > 将字符串数组存储到 mongoDB 集合中

问题描述

我很陌生MongoDBmongoose我有一个名为的模型名称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。

但我正在寻找一些更好的方法,比如不需要将字符串数组转换为对象数组。

标签: mongodbmongoose

解决方案


您必须使用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 
}); 

推荐阅读