Home > Software engineering >  Can't get collection array from mongoDB with mongoose query
Can't get collection array from mongoDB with mongoose query

Time:10-31

I have problem with getting data from DB. I want to get "collections" Array from mongoDB and render it in table component, but query returns null because of problem "user not found". Interesting thing is that if I use {email: req.body.email} in updateOne query to search for user and then create new collection it works and user is found. getCollections.js

const router = require("express").Router();
const User = require("../models/user");

router.get("/", (req, res) => {
  var query = { email: req.body.email };

  User.find(query, (err, result) => {
    if (err) {
      res.json({ status: "error", error: "User not found" }, err);
    } else {
      res.json(result);
    }
  });
});
module.exports = router;

frontend getCollections query

useEffect(() => {
    const url = "http://localhost:5000/api/getCollections";
    // const url = `https://item-collection-app-bz.herokuapp.com/api/getCollections`;
    axios
      .get(url, { email: localStorage.getItem("email") })
      .then((response) => {
        setListOfCollections(response.data);
      });
  });

user.js UserSchema

const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  _id: { type: mongoose.Schema.Types.ObjectId, required: true },
  username: { type: String, require: true },
  password: { type: String, require: true },
  email: { type: String, require: true },
  admin: { type: Boolean },
  blocked: { type: Boolean },
  collections: [
    {
      _id: { type: mongoose.Schema.Types.ObjectId, required: true },
      coll_name: { type: String },
      type: { type: String },
      coll_desc: { type: String },
      coll_image: { type: String },
      items: [
        {
          _id: { type: mongoose.Schema.Types.ObjectId, required: true },
          item_name: { type: String },
          item_desc: { type: String },
          comments: [
            {
              user: { type: String },
              comment: { type: String },
              comment_id: { type: String },
            },
          ],
          likes: { type: Number },
          item_image: { type: String },
          upload_date: { type: String },
        },
      ],
    },
  ],
});

userSchema.methods.generateAuthToken = function () {
  const appToken = jwt.sign({ _id: this._id }, process.env.JWTPRIVATEKEY, {
    expiresIn: "7d",
  });
  return appToken;
};

const User = mongoose.model("user", userSchema);

module.exports = User;

mongoDB mongoDB structure

Tried User.findOne(), User.find()

SOLUTION

Thank you @Varun Kaklia. The solution is changing router.get and axios.get to router.post and axios.post.

CodePudding user response:

Hey @1zboro1 first check did you receive any data from frontend inside Routes like-

const router = require("express").Router();
const User = require("../models/user");

router.get("/", (req, res) => {
const email = req.body.email;
console.log("Email from frontend", email)
  var query = { email: req.body.email };
  if (email != null || undefined) {
try {
  const user = await User.find({ email});
  console.log("User Details in User Routes of Backend",user)
  if (user.length > 0) {
    const currentUser = {
      name: user[0].name,
      email1: user[0].email1,
      isAdmin: user[0].isAdmin,
      _id: user[0]._id,
    };
    // console.log("Get User in User Routes of Backend", currentUser)
    res.status(200).send(currentUser);
  }
} catch (error) {
  res.status(404).json({
    message: "Something Went wrong",
    
  });
}

Hope this code solve your query and give you desired result. If you still facing issue lemme know. Thanks

  • Related