Ad

How To Fix ' I Have Author & Book Schema, In Postman Result, I Want To Show Two Or More Author For A Book'

I want to postman result like this

[{
 title:
 year:
 rating:
 authors: [{
    name: 
    birthday:
    country: 
  }]
}]

i want two or more author, but I got only one author

 model/book.js

  const mongoose = require('mongoose');
  const authorSchema = require('../models/author');


 const bookSchema = new mongoose.Schema({
   title:{
       type:String,
       required:true,
       min: 5,
       max: 50
   },
   rating:{
       type: Number,
       required: true,
       min:0,
       max:10
   },
   authors: {
       type: authorSchema,
       required: true
   },

 });
   const Book= new mongoose.model('Book', bookSchema);



route/book.js

router.get('/', async(req, res)=>{
    const books= await Book
    .find({}, { _id:0, __v:0 })
     res.send(books);
});  

router.post('/', async(req, res)=>{
const author = await Author.findById  (req.body.authorId);
if(!author) return res.status(400).send('Invalid Author');

let book= new Book({
    title: req.body.title,
    rating: req.body.rating,
    authors:[{
        name: author.name,
        birthday: author.birthday,
        country: author.country
    }]
});

book= await book.save();
res.send(book)

});
module.exports =router;

I enter this by POST Method in postman
{ "title": "Learn Python", "rating": "9", "authorId": [ "5d99ac95f17917117068631b", "5d99ad75c4edd61f98af740b"]
}

then I get Only first author, author array not show

Ad

Answer

findById finds a single document by provided _id field

Use find with $in to match the number of documents with an array of _id.

Author.find({ $in: req.body.authorId }) will give you an array of authors matched with with req.body.authorId.

and then create an author array by looping over the result from find query for your new Book instance.

Suggestion

Use only the fields you require from a find query - eg Author.find({ $in: req.body.authorId }, 'name birthday country'),

also, if you have a another collection of Author, it is better to keep the reference(_id) in Book collection instead of passing author details, this will remove the data redundancy from you collections. You can find out more about data modelling in mongodb here

Ad
source: stackoverflow.com
Ad