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

279
Vistas
mongoose pull specific data from single document

So Im using mongoose and mongo atlas. I have a single document with a structure as follows:

{_id: ObjectId("3u3ui4t432) ,
name: cat1,
items : 
    [
    {cat1_item1: "something"},
    {cat1_item2: "something"}
   ]}

{_id: ObjectId("3u3uir3bi2) ,
name: cat2,
items : 
    [
    {cat2_item1: "something"},
    {cat2_item2: "something"}
   ]}

currently this endpoint retrieves the entire document, i am just trying to access one category at a time based of a param either url or body

//this gets the specific document i want, but i would prefer to get that document through something like this.
// findOne({ category: req.body.category })
app.post('/targetCategory', async (req, res) => {
    const categoryName = req.body.category
    categoryCollection.findOne({ _id: "62b9353730ac42a7d390f5ad" }, (err, 
data) => {
        if (err) {
            console.log(err)
        } else {
            res.send(data)
            console.log(categoryName)
        }
    })
})
const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const categorySchema = Schema({
    categories: {

    }
})

module.exports = mongoose.model('categoryCollection', categorySchema)

basically I want to use params(?) to only access one category at a time to minimise data sent to the frontend. How do i go about using something like findOne() with the param being either category1 or category2 as I only want the array inside. I am using mongoose, node and express.

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

0

model

const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const categorySchema = Schema({
    name: String,
    // items placeholder, modify if required
    items: String[]
})

const Category = mongoose.model('Category', categorySchema)
module.exports = Category

the controller you can use

app.post('/listOne', async (req, res) => {
  try {
    const categoryData = await Category.findOne({name: req.body.category})
    res.send({category: categoryData})
  }
  catch (e) {
    console.log(e)
  }
})

another controller solution I suggest

app.get('/category/:name', async (req, res) => {
  try {
    const categoryData = await Category.findOne({name: req.params.name})
    res.send({category: categoryData})
  }
  catch (e) {
    console.log(e)
  }
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

To find single data in collection you can use this function or read this in mongoose docs https://mongoosejs.com/docs/api.html#model_Model.findOne

// Find one adventure whose `country` is 'Croatia', otherwise `null`
await Adventure.findOne({ country: 'Croatia' }).exec();

// using callback
Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {});

// select only the adventures name and length
await Adventure.findOne({ country: 'Croatia' }, 'name length').exec();

and to get parameter in express you can use this

app.get('/users/:userId/books/:bookId', (req, res) => {
    res.send(req.params)
})
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