Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

367
Vistas
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.

I created three different schemes that are somehow related to each other e.g. 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.

Here is a part of the 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.

###
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. 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). 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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

There is difference between Mongoose and MongoDB native driver. Mongoose will automatically convert(Typecast) into Type defined in schema.

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})
    }
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda