【问题标题】:How to fix ' I have author & book schema, In Postman result, I want to show two or more author for a book'如何修复“我有作者和书籍架构,在 Postman 结果中,我想为一本书显示两个或多个作者”
【发布时间】:2019-10-07 13:59:35
【问题描述】:

我想要这样的邮递员结果

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

我想要两位或更多作者,但我只有一位作者

 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;

我在邮递员中通过 POST 方法输入这个
{ "title": "学习 Python", “评分”:“9”, “作者ID”:[“5d99ac95f17917117068631b”, "5d99ad75c4edd61f98af740b"]
}

然后我得到只有第一作者,作者数组不显示

【问题讨论】:

  • “authorSchema”是什么样的?
  • const authorSchema= new mongoose.Schema({ name:{ type: String, required: true, min: 5, max:50 },birthday:{ type: String, required: true }, 国家:{ 类型:字符串,必需:true } }); const Author = new mongoose.model('Author', authorSchema);

标签: node.js express mongoose model mongoose-schema


【解决方案1】:

findById 通过提供的 _id 字段查找单个文档

使用find$in 来匹配带有_id 数组的文档数。

Author.find({ $in: req.body.authorId }) 将为您提供与req.body.authorId 匹配的作者数组。

然后通过循环从find 查询您的new Book 实例的结果来创建作者数组。

建议

仅使用 find 查询中需要的字段 - 例如 Author.find({ $in: req.body.authorId }, 'name birthday country')

另外,如果您有另一个Author 集合,最好将引用(_id)保留在Book 集合中,而不是传递作者详细信息,这将删除您集合中的数据冗余。 您可以在 mongodb here 中了解更多关于数据建模的信息

【讨论】:

  • 我是 node.js 的新手,我不明白如何通过循环结果来创建作者数组。
  • 你可以这样做let authorList = authors.map((author) => ({ name: author.name, birthday: author.birthday, country: author.country })) 并在new Book 实例中使用这个authorList
猜你喜欢
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 1970-01-01
相关资源
最近更新 更多