简体   繁体   English

发布时如何在http语句中使用object_id引用另一个模型? (蒙戈数据库)

[英]How to refer to another model using object_id in a http statement when posting? (mongo db)

I'm using a mongodb to create the REST API for an express app with node.js.我正在使用 mongodb 为带有 node.js 的快速应用程序创建 REST API。

I created three different schemes that are somehow related to each other eg a book was written by an author and published by a publisher.我创建了三个不同的方案,它们以某种方式相互关联,例如一本书由作者编写并由出版商出版。 Here is the scheme for the book.这是本书的方案

const mongoose = require('mongoose')

const bookSchema = new mongoose.Schema({

    title: {
        type: String,
        required: true

    }, 
    author: {
        type: {type: mongoose.Schema.Types.ObjectId, ref: 'Author'},

    },
    publisher: {
        type: {type: mongoose.Schema.Types.ObjectId, ref: 'Publisher'},

    },
    isbn: {
        type: String,
        required: true

    },

})

module.exports = mongoose.model('Book', bookSchema)

Each of those schemes has an id, but I'm using the default id that is generated when posting an object.这些方案中的每一个都有一个 id,但我使用的是发布对象时生成的默认 id。

Here is a part of the route-file .这是route-file的一部分。

//Creating one Book
router.post('/', async (req, res) => {
    const book = new Book({
        title: req.body.title,
        author: req.body.author.findById,
        publisher: req.body.publisher.findById,
        isbn: req.body.isbn
    })

    try {
        const newBook = await book.save()
        res.status(201).json(newBook)
    } catch {
        res.status(400).json({message: err.message})
    }
})

I am using a .rest-file for testing .我正在使用.rest 文件进行测试

###
POST http://localhost:3000/books
Content-Type: application/json

{
    "title" : "test",
    "author" : "615c429dfe31a3863b6ebc8e", //object_id of an author in the db
    "publisher" : "615f3daf330081bcd5010861", //object_id of a publisher in the db
    "isbn" : "1234"
}

When I run this statement it will just create an object containing the object_id, a title and an isbn.当我运行这个语句时,它只会创建一个包含 object_id、标题和 isbn 的对象。 The author and the publisher are left out.作者和出版商被排除在外。 I did not set author and publisher as required in the scheme because it would throw an error (failed to cast string to object_id).我没有按照方案的要求设置作者和出版商,因为它会抛出错误(无法将字符串转换为 object_id)。 I already tried that.我已经试过了。

Can anyone please tell me how to avoid this casting error?谁能告诉我如何避免这种铸造错误? I already googled and watched tutorials, but i did not find anything, yet.我已经用谷歌搜索并观看了教程,但我还没有找到任何东西。

Thank you.谢谢你。

There is difference between Mongoose and MongoDB native driver . MongooseMongoDB 本机驱动程序之间存在差异。 Mongoose will automatically convert(Typecast) into Type defined in schema. Mongoose会自动将(Typecast) 转换为模式中定义的类型。

Your schema looks fine, you just need to change it like你的架构看起来不错,你只需要像

//Creating one Book
router.post('/', async (req, res) => {
    const book = new Book({
        title: req.body.title,
        author: req.body.author,
        publisher: req.body.publisher,
        isbn: req.body.isbn
    })

    try {
        const newBook = await book.save()
        res.status(201).json(newBook)
    } catch {
        res.status(400).json({message: err.message})
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM