Home > Blockchain >  How To Insert this mongodb document to collection using postman
How To Insert this mongodb document to collection using postman

Time:03-26

I tried My Collection Structure like this is in node

app.collection('person').insertOne({
    name: req.body.name,
    details: [{
        age: req.body.details.age,
        town: req.body.details.town
    }]
});

In Postman I tried Like This

{
    "name": "abc",
    "details:[ {
        age: "1",
        town: "efg"
    },
    {
        age: "2",
        town: "jkl"
    }]
}

I get null values in my result. I need to know how to send this data to mongodb using nodejs with postman

CodePudding user response:

1- create an endpoint to handle post requests that are coming from postman (on my case I'm using express)

const express = require("express")                                    
const app = express()  
app.use(express.json()) 

const client = new MongoClient(your_url);
await client.connect(); //nodejs verson 14  support top level await
const collection = client.db(your_db_name).collection('person');

app.post("/register", async (req, res) => {
   console.log(req.body) //check the values on the console
   try {
    await collection.insertOne({
      name:req.body.name,
      details:[{
      age:req.body.details.age,
      town:req.body.details.town
      }]
      });
   } catch (error) {
     console.log(error)
   }
});

app.listen(3000,()=>console.log('app is on!'))

2-make sure that you connected successfully to your databse

3- go to your postman, send a POST request to http://localhost:3000/register and make sure to add a Body to your request (Body --> raw --> JSON) with the json data that you want to send.

CodePudding user response:

You can update your update query implementation to match incoming request payload mapping the req.body.details directly to the document detailsfield:

app.collection('person').insertOne({
    name: req.body.name,
    details: req.body.details,
});

Otherwise you have to use Array#reduce to transform your input array to match your desired storage structure.

  • Related