简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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