Home > Mobile >  How to POST data to an Array in API
How to POST data to an Array in API

Time:08-19

I have the following API

{
  "author": [],
  "categories": [],
  "_id": "62ff04704bcdbd99716e0cc4",
  "kind": "books",
  "items": [
    {
      "title": "Java",
      "author": [
        "John",
        "Peter"
      ],
      "publisher": "North Publishers",
      "publishedDate": "12 Sep 2021",
      "description": "Learn Java",
      "pageCount": 286,
      "printType": "PaperBack",
      "categories": [
        "Programming",
        "Java"
      ],
      "language": "English",
      "price": 1856
    }
  ]
}

I want to send a POST request which will add data in "Items" array in the above API

I have the following code in my schema.js

const {Schema, default:mongoose} = require('mongoose');
const bookSchema = new Schema([{
       kind:String,
       title:String,
       author:[String],
       publisher:String,
       publishedDate:String,
       description:String,
       pageCount:Number,
       printType:String,
       categories:[String],
       language:String,
       price:Number,
}]);
const ItemSchema = new Schema([{
       items:[bookSchema]
}])
const book = mongoose.model('book',ItemSchema);
module.exports = book;

I have the following code in my routes.js file

const express = require('express');
const app = express();
const BookSchema = require('./schema');

app.post('/books', async (req,resp)=>{
   await BookSchema.find({items:'[ ]',function(err,data){
    if(err){
        console.log(err);
    }
    else{
        data.push(req.query)
    }
   }});
   resp.status(200).send("Success")

But i cannot add the data from req.query to the "Items" array using this method

Can anyone tell me the right way of doing this

CodePudding user response:

You should close the filter of the find function, also if you want to use async await you should write:

app.post('/books', async (req, resp) => {
  try {
    const items = await BookSchema.find({ });
    items.push(req.query);
    resp.status(200).send('Success');
  } catch (err) {
    resp.status(400).send('Error');
  }
});

Also, if you want to filter an array of objects you should specify the property, for example:

{ 'items.kind': 'Some king' }

CodePudding user response:

Are you sure the data that you are pushing in the req.query? Can you show me how you pass the data when you call the API?

In general, the data of POST method should be in the body req.body, something like:

const express = require('express');
const app = express();
const BookSchema = require('./schema');

app.post('/books', async (req,resp)=>{
   await BookSchema.find({items:'[ ]',function(err,data){
    if(err){
        console.log(err);
    }
    else{
        data.push(req.body)
    }
   }});
   resp.status(200).send("Success")
  • Related