0

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.

0

1 Answer 1

1

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 
}); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.