I am using mongoose and express to access data within MongoDB and I can see the JSON when I make a reference to the database, but when I try to target an object nested inside, I get an undefined message.
JS file to access DB.
const express = require('express');
const router = express.Router();
const skate_tricks = require('../models/SkateTrick');
router.get('/', (req, res) => {
skate_tricks.find({}, (err, result) => {
if (err) {
res.send(err);
} else {
res.send(result);
}
});
});
module.exports = router;
Results snippet using Postman
[
{
"trick_type": [],
"_id": "5f34a5782e0d2fe1c2847633",
"tricks": [
{
"trick_id": 0,
"trick_name": "ollie",
"trick_type": [
"flat"
],
"trick_difficulty": "n",
"trick_description": "Fundamental trick involving jumping with the skateboard. Performed by popping the tail with the back foot and sliding the front foot up towards the nose of the board. The sliding action levels the board while you are airborn."
}
]
}
]
I want to access the "tricks" array of objects directly, but it's not working.
res.send(result.tricks);
You result object is an array of object.
[
{
"trick_type": [],
"_id": "5f34a5782e0d2fe1c2847633",
"tricks": [
{
"trick_id": 0,
"trick_name": "ollie",
"trick_type": [
"flat"
],
"trick_difficulty": "n",
"trick_description": "Fundamental trick involving jumping with the skateboard. Performed by popping the tail with the back foot and sliding the front foot up towards the nose of the board. The sliding action levels the board while you are airborn."
}
]
}
]
So you have to access it by using res.send(result[0].tricks);
or change your API response to return it like
Try to add tricks
to your mongoose model
const mongoose = require("mongoose");
const SkateTrickSchema = new mongoose.Schema({
trick_id: { type: Number, required: true, unique: true },
trick_name: { type: String, unique: true },
trick_type: { type: Array, required: true },
trick_difficulty: { type: String, required: false },
trick_description: { type: String, required: false },
tricks: { type: Array, required: true }
});
module.exports = SkateTrick = mongoose.model(
"skateboard-tricks",
SkateTrickSchema
);
One thing what you can try is to add .lean()
to your query
router.get("/", async (req, res) => {
try {
let result = await skate_tricks.find({}).lean();
res.send(result);
} catch (err) {
res.send(err);
}
});
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.