0

The server return me an empty json, I think there is some problem with the mongoose method find() that doesn't find nothing. Here's the code:

inde.js:

const express = require('express');
const router = express.Router();

const Folders = require('../bin/models/folders');

router.get('/:id', function (req, res) {
    Folders.find({ 'BeaconId': req.params.id }).exec((err, folders) => {
        if (err) return res.status(500).json({ error: err });
        if (!folders) return res.status(404).json({ message: 'Folder not found' });
        res.json(folders);
    });
});
module.exports = router;

folders.js:

onst mongoose = require('mongoose');

const folderSchema = mongoose.Schema({
    Name_folder: String,
    Link_folder: String,
    BeaconId: Number
});

const Folders = mongoose.model('Folders', folderSchema, 'folders');

module.exports = Folders;
Giulia
  • 11
  • 4
  • what error you get or you just get an empty json? and have you checked what you get in `req.params.id`? – 1sina1 Mar 11 '22 at 12:51
  • 1
    I'm thinking that `req.params.id` is a _String_ not a _Number_ – Gabriel Rodríguez Flores Mar 11 '22 at 12:55
  • I just get an empty json. Id is a Number and is the beaconId – Giulia Mar 11 '22 at 13:11
  • Do you have a previus parser to change the Id to Number ? If not, you are getting a String. Check that with `typeof req.params.id` – Gabriel Rodríguez Flores Mar 11 '22 at 13:24
  • Ok I think I did it changing BeaconId into String in the schema, thank you so much for your help!!!!! May I ask some help for this problem too: https://stackoverflow.com/questions/71432270/why-my-android-studio-app-cant-reach-my-nodejs-server?noredirect=1#comment126269880_71432270 – Giulia Mar 11 '22 at 13:51

1 Answers1

0

Query params are always a string, so you can try to change the BeaconId from Number to String in the mongooseSchema:

const folderSchema = mongoose.Schema({
    Name_folder: String,
    Link_folder: String,
    BeaconId: String
});

or alternatively you can convert the string query.params.id to number:

{ 'BeaconId': parseInt(req.params.id)}
biorubenfs
  • 643
  • 6
  • 15