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.
2
Answers
model
the controller you can use
another controller solution I suggest
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
and to get parameter in express you can use this