I have an API as follows
{
"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 get the "Items" Array from the API using Express JS
In the routes.js i have the following code :-
const express = require('express');
const app = express();
const BookSchema = require('./schema');
app.get('/books', async (req,resp)=>{
const book = await BookSchema.find({ });
var BookArray = book[0]
console.log(BookArray.items)
})
After sending a GET request i get "Undefined" in the console but i wanted the array
For reference this is the schema.js file
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 book = mongoose.model('book',bookSchema);
module.exports = book;
And this is my server.js file
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const router = require('./routes');
mongoose.connect('mongodb://localhost:27017/book')
app.use(express.static('static'));
app.use(router);
app.listen(5000,()=>{
console.log("Server is running at http://127.0.0.1:5000");
})
How do i get the array from the API
CodePudding user response:
You should also add items to the book schema. You can create nested schemas like so:
const ItemSchema = mongoose.Schema({
title: String,
author: [String],
publisher: String,
publishDate: String,
description: String,
pageCount: Number,
printType: String,
categories: [String],
language: String,
price: Number
});
const bookSchema = new Schema([{
...
items: [ItemSchema],
}]);
const book = mongoose.model('book',bookSchema);
module.exports = book;
You can read more about it here