Home > front end >  mongoose pull specific data from single document
mongoose pull specific data from single document

Time:06-27

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.

CodePudding user response:

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)
  }
})

CodePudding user response:

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)
})
  • Related