简体   繁体   中英

How to read out NodeJS form Data and write to MongoDB

I've created a simple dynamic single page form which renders a number of fields based on x number of people. I've used the extended setting in the body parser to submit nested objects in my html.

When I console log req.body I get this:

    {
    user: {
        '10': {
            attending: '1',
            dietaryRequirements: 'None'
        },
        '11': {
            attending: '0',
            dietaryRequirements: 'Not Applicable'
        }
    }
}

What would be the easiest way to read out the ID (10 & 11) and write the attending and dietary requirement fields to MongoDB. Thanks for any help!

Well, you have to define a Schema first of all.

//this is ../models/user.model file

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//Define user model schema
const userSchema = new Schema({
    _id: String,
    attending: { type: Number, required: true },
    dietaryRequirements: String,
}, {
    timestamps: true
});
const User= mongoose.model('users', userSchema );
module.exports = User;

Then, you have got user as an object so you need to insert data into array as objects.This each object need to mach to Schema that you defined. when you add user objects to array you can easily call mongoose insertMany() method that came from User Schema.

const User= require('../models/user.model');
const { user } = req.body;
console.log(user );
let userItems= Object.keys(user).map(userItem => {
         return {
               _id: userItem,
               attending: user[userItem ].attending,
               dietaryRequirements: user[userItem ].dietaryRequirements,
          }
 });
 try {
      await User.insertMany(userItems);

      res.status(200).json({ status: true });
  } catch (error) {
      console.log(error);
  }

this User.insertMany(userItems) method 'await' until all data save in mongo db hence you have to use 'async' keyword in express router.

For more here

update multiple random users

Here you can use asynchronous loop then code will be fast.

let updateResponces = await Promise.all(userItems.map(user=>{
   User.updateOne({ _id: user._id }, { attending: 'true'});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM