Mongoose - 使用ExpressJS发送Post请求时如何避免数据冗余?

时间:2017-11-02 00:07:53

标签: express mongoose

我在创建图书出版商系统时学习了MEAN Stack。 我在编程方面很陌生,而且我没有成功地研究了很多答案。

我想使用Express发送Post请求,当Mongoose保存bookSchema.author时,我希望它保存authorSchema中的名字和姓氏。当我向Mongoose发送Get请求时,我希望收到保存在authorSchema中的作者保存的书。

我创建了2个Mongoose Schema:

图书架构:

    const bookSchema = new Schema ({
    name:{
        type    :String, 
        required: true},
    isbn:{
        type    :Number,
        min: 1000000000000,
        max: 9999999999999,
        required: true
    },
    price:{
        type    :Number, 
        required: true},
    page:{
        type    :Number, 
        required: true},
    author:{
        type    :String,
        required: true},
})

作者架构:

const authorSchema = new Schema({
first_name:{
    type: String,
    required: true
},
last_name:{
    type: String,
    required: true
}})

Express Post功能:

route.post('/addBook', (req, res)=>{
    let newBook = new book({
            name: req.body.name,
            isbn: req.body.isbn,
            price: req.body.price,
            page: req.body.page,
            author: req.body.author
    })
    newBook.save((err, bookSaved)=>{
        if (err){
            res.send(err)
        }
        else{
            const bookName = req.body.name
            res.send(bookName + ' salvo.')
        }
    })
})

0 个答案:

没有答案
相关问题