MongoDB req.body Issue

允我心安 提交于 2020-01-03 05:25:49

问题


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>

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/57914706/mongodb-req-body-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!