CarlosDnl
CarlosDnl

Reputation: 65

Mongoose return all array data

I am working in a nodejs rest api using mongodb and want return all array data from the next structure

[
    {
        "inventorydata": [
            [
                {
                    "location": "principal",
                    "code": "123",
                    "description": "prueba 1"
                },
                {
                    "location": "secundaria",
                    "code": "456",
                    "description": "prueba 2"
                },
                {
                    "location": "tercera",
                    "code": "789",
                    "description": "prueba 3"
                }
            ]
        ],
        "_id": "5fff69999119ae1a049955d3",
        "inventory_code": "ed9825f7-647b-443d-8e4c-69acf30cb292",
        "createdAt": "2021-01-13T21:43:53.318Z",
        "__v": 0
    }
]

I am trying to return all items from inventoryData using the following code inside nodejs

app.post('/get', async (req, res) => {
  try {
    const item = await imgModel.find({ 'inventorydata' : { $elemMatch: { } } });
    res.json(item)
  } catch (e) {
    res.json({ error_code: 1, err_desc: "Corupted excel file" });
  }

});

This is the expected output for the nodejs response

[
                {
                    "location": "principal",
                    "code": "123",
                    "description": "prueba 1"
                },
                {
                    "location": "secundaria",
                    "code": "456",
                    "description": "prueba 2"
                },
                {
                    "location": "tercera",
                    "code": "789",
                    "description": "prueba 3"
                }
            ]

Upvotes: 0

Views: 40

Answers (1)

J.F.
J.F.

Reputation: 15235

You can use projection to return values you want.

Also using mongoose you can access your data using JS in this way:

yourModel.find({/*your_query*/},{"inventorydata": 1}).then(result => {
  console.log("inventorydata = ",result.inventorydata)
}).catch(e => {
  // error
})

Example here

Upvotes: 1

Related Questions