简体   繁体   中英

Send multiple data on nodejs to mongodb using postman

So, I'd like to send multiple data(json) using postman. for example I've got two data json. I wanna send that json to mongodb using postman at same time like that. But I got an error

SyntaxError: Unexpected token , in JSON at position 168<br> and so on.

So I've tried wrap that object to the array. And I got an error

Products validation failed: title: Path `title` is required., type: Path `type` is required., description: Path `description` is required., filename: Path `filename` is required., price: Path `price` is required., rating: Path `rating` is required.

I'm sure all the data has filled.

My goal I wanna send a lot of data json like that. Not just one or two. Like ten or more but just once send.

Example json I want to send to mongodb

{
  "title": "Asparagus",
  "type": "vegetable",
  "description": "Asparagus with ham on the wooden table",
  "filename": "2.jpg",
  "price": "18.95",
  "rating": "3"
}, {
  "title": "Green smoothie",
  "type": "dairy",
  "description": "Glass of green smoothie with quail egg's yolk, served with cocktail tube, green apple and baby spinach leaves over tin surface.",
  "filename": "3.jpg",
  "price": "17.68",
  "rating": "4"
}

schema

const productSchema = new mongoose.Schema({
    title: {type: String, required: true},
    type: {type: String, required: true},
    description: {type: String, required: true},
    filename: {type: String, required: true},
    price: {type: Number, required: true},
    rating: {type: Number, required: true},
    date: {type: Date, default: Date.now}
});

Routes (post route)

const Product = require('../models/product.js');
routes.post('/', async (req, res) => {
  const product = new Product({
    title: req.body.title,
    type: req.body.type,
    description: req.body.description,
    filename: req.body.filename,
    price: req.body.price,
    rating: req.body.rating
  });
  try {
    const new_product = await product.save();
    return res.status(201).json(new_product);
  }catch(err){
    return res.status(400).json({error: err.message});
  }
});

Thank you

Apologies if you have thought of this, but it's possible to pass an array in Postman then have your route.forEach on the elements of the array to store in the database.

You could even set a conditional to check if it's an array first if you sometimes want to send a single object.

You will have to send the JSON as an array.

[{
  "title": "Asparagus",
  ...
}, {
  "title": "Green smoothie",
  ...
}]

Then you can access it like this:

req.body.forEach(item => {
  // do something with item
})

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