Home > Software design >  There is some issue when I try to get data from mongodb by node.js?
There is some issue when I try to get data from mongodb by node.js?

Time:10-11

This is my index.js. When I hit my API using postman, there is a bug in my getdata() method code that causes it to return the else statement rather than finding the requested resource. I'm not sure why the data targeting by ID can't be found. When I use console.log to test my code, the try statement is entered but did not find anything from the database and catch statement is returned.

const connectToMongo = require('./db');
var cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
const photo = require('./models/photoModel');
const formidable = require('formidable');
const fs = require('fs');
const photoModel = require('./models/photoModel');

connectToMongo();
const app = express();
app.use(cors());
const port = 5000;

//app.use(express.json());
app.use(bodyParser.json());

const userData = (req, res) => {
  const form = new formidable.IncomingForm();
  console.log('1');
  form.parse(req, (err, fields, file) => {
    console.log('2');
    if (fields) {
      console.log('3');
      const { email, mno, name } = fields;
      if (!email || !mno || !name) {
        console.log('4');
        return res.status(400).json({
          error: 'Fill all the fields',
        });
      }
    }
    if (file.photo) {
      if (file.photo.size > 4000000) {
        return res.status(400).json({
          error: 'image size is too long',
        });
      }
      const user = new photo(fields);
      user.photo.data = fs.readFileSync(file.photo.filepath);
      user.photo.contentType = file.photo.type;

      user.save((err, user) => {
        if (err) {
          return res.status(400).json({
            error: 'Not save in db',
          });
        }
        console.log('above json');
        res.json(user);
      });
    }
  });
};

// The issue is here
const getdata = async (req, res) => {
  try {
    console.log('yes');
    const photo = await photo.find({ photo: req.photo.id });
    res.json(photo);
  } catch (error) {
    return res.status(400).json({
      error: 'not find',
    });
  }
};

//router
app.post('/userdashboard', userData);
app.get('/getdata', getdata);

app.listen(port, () => {
  console.log(`Dashboard Backend listening on port ${port}`);
});

This is my modelschema

const mongoose = require('mongoose');
const { Schema } = mongoose;
const PhotoSchema = new Schema({
    name:{
        type:String,
        trim:true,
        required:true
    },
    email:{
        type:String,
        trim:true,
        required:true
    },
    photo:{
        data:Buffer,
        contentType:String
    },
    mno:{
        type:Number,
        required:true
    }

  });

  module.exports=mongoose.model('photo',PhotoSchema);

CodePudding user response:

First mistake you did was not adding console.error(error), if you did it would have shown exact error message. In this case req.photo is undefined and you are trying to access id property of undefined which causes error to be thrown.

const getdata = async (req, res) => {
  try {
    const { photo } = req.body

    // TODO: use custom error class for validation errors instead of default Error class
    if (!photo) throw new Error('photo is missing')
    if (!photo.id) throw new Error('photo.id is missing')
    // TODO: validate photo.id is valid monogoid 
    
    const photos = await photo.find({ photo: photo.id })
    res.json(photos)
  } catch (error) {
    console.error(error) // <-- this was missing
    res.status(400).json({ error: 'not find' }) // provide good error message
    return
  }
}

CodePudding user response:

See the thing is you're passing photo's ID in the photo property of your schema which is a buffer type and don't accept objectId. You have to pass req.photo.id in _id property of your schema.

const getdata=async (req,res)=>{
try {
 console.log('yes')
 const photo=await photo.find({_id:req.photo.id})
 res.json(photo)
} catch (error) {
 return res.status(400).json({
  error:"not find"
})
}
  • Related