AndrewLeonardi
AndrewLeonardi

Reputation: 3512

MongoDB req.body Issue

I have a very simple Mongo set up as shown below. This works perfectly to get data from an input field and save the data. All working.

My Question: How would I go about looping through the jobs variable on the front end and set the data up so that it would work with my model. Somehow I would need to get it into inputs so I can req.body?

Data:

var jobs = [
{   
name: "Accountant"
salary: 0,
}, {
name: "Actor"
salary: 0,
}, {
name: "Actuary"
salary: 0
}]... + hundreds more... 

My Mongo Schema:

var JobSchema = new mongoose.Schema({
    name: String,
    salary: Number
});

module.exports = mongoose.model('jobs' , jobSchema)

My post route:

router.post('/register', function(req, res) {
    var job = ({
    name:   req.body.name,
    salary: req.body.salary,
    })

Form to post:

<form action="/register" method="post">
    <textarea class='jobnames' type="text" name="name" placeholder="name"> </textarea>
    <textarea class='2' type="number" name="salary" placeholder="salary"> </textarea>
    <button >Submit</button>
</form>

Upvotes: 2

Views: 2413

Answers (2)

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

You can try it using the insertMany() query .

req.body = [
  {
    name: "Accountant",
    salary: 0,

  },
  {
    name: "Actor",
    salary: 0,

  },
  {
    name: "Actuary",
    salary: 0
  }
]

db.collection.insertMany(req.body);

With the help of this query , you can insert multiple documents at a time .
unique id i.e., _id will be automatically generated .

For more information about insertMany() visit the official document

Upvotes: 2

JBaczuk
JBaczuk

Reputation: 14589

You can just create it with the array itself, i.e. pass the array jobs in the post request. For example:

// set up the model using the schema
var Job = mongoose.model('Job', JobSchema);

Job.create(req.body)
.then(records => console.log('created records', JSON.stringify(records, null, 2))

see Model.create

Upvotes: 0

Related Questions