Search code examples
node.jsexpressmongoosemodelmongoose-schema

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


Solution

  • 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