ayush verma
ayush verma

Reputation: 35

Store array of string into the mongoDB collection

I am very new to MongoDB and mongoose I have a model name called 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;

Now I have a array of string:

const agentName = ['john', 'alex', 'david'];

Now I want to store this array into the mongoDB as an individual agent.

like this:

[
    {
        "_id": "6000977d9b94f52960955066",
        "agent": "john",
        "__v": 0
    },
    {
        "_id": "6000977d9b94f52960955067",
        "agent": "alex",
        "__v": 0
    },
    {
        "_id": "6000977d9b94f52960955068",
        "agent": "david",
        "__v": 0
    }
]

Note: Right now First I am converting my array of string into the array of object using loop like this:

agentName = agentName.map((e) => {return {agent: e}})

//output of above line of code

[ { agent: 'Alex Watson' },
  { agent: 'John Snow' },
  { agent: 'Rita Ora' } ]

Then I am saving the agentName.

But I am looking for some better approach, Like in which there is no need of converting the array of string into the array of object.

Upvotes: 0

Views: 1688

Answers (1)

Mohammad Yaser Ahmadi
Mohammad Yaser Ahmadi

Reputation: 5041

you must to use insertMany() function is used to insert multiple documents into a collection. It accepts an array of documents to insert into the collection. like following code, so have to create a array of abjects, that you created

note: in your question define const agentName next step assign result of map to the constant variable, so this is wrong

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 
}); 

Upvotes: 1

Related Questions