0

I'm a total beginner with node, and I've looked everywhere for answer, but I can't seem to resolve this issue. I'm using express, mongoose and Vuex.

I basically want to define two endpoints-one for getting photos for a specific user, and another that gets all photos by all users. My first endpoint is /api/photos, and it works perfectly, but /api/photos/all always catches an error. However, I know that there's nothing wrong with the way I'm making the request in Vuex because if I replace the code inside /photos with the code intended for /photos/all it works. I've tried all kinds of alternatives to /photos/____ but it seems like it doesn't like the path? The node error doesn't help because it says

CastError: Cast to ObjectId failed for value "all" at path "_id" for model "Photo"

but I know that's not the issue, because both calls work when I define the endpoint as /photos instead.

Here's my store.js

async getAllPhotos(context) {
  try {
    let response = await axios.get("/api/photos/all");
    context.commit('setPhotos', response.data);
    return "";
  } catch (error) {
    return "";
  }
},
async getOnePhoto(context, id) {
  try {
    let response = await axios.get("/api/photos/" + id);
    context.commit('setSelectedPhoto', response.data);
  } catch (error) {
    return "";
  }
},

my photo.js:

const mongoose = require('mongoose');
const express = require("express");
const router = express.Router();
const auth = require("./auth.js");

// Configure multer so that it will upload to '/public/images'
const multer = require('multer')
const upload = multer({
    dest: '../public/images/',
    limits: {
        fileSize: 10000000
    }
});

const users = require("./users.js");
const User = users.model;

const photoSchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.ObjectId,
        ref: 'User'
    },
    path: String,
    title: String,
    description: String,
    name: String,
    created: {
        type: Date,
        default: Date.now
    },
});

const Photo = mongoose.model('Photo', photoSchema);
// get photos for user
router.get("/", auth.verifyToken, User.verify, async (req, res) => {
    try {
        let photos = await Photo.find().sort({
          created: -1
        }).populate('user');
        return res.send(photos);
      } catch (error) {
        console.log(error);
        return res.sendStatus(500);
      }
});

// get all photos THIS DOESNT WORK NO MATTER WHAT CODE GOES IN
router.get("/all", async (req, res) => {
    // return photos
    try {
        let photos = await Photo.find({
            user: req.user
        }).sort({
            created: -1
        });
        return res.send(photos);
    } catch (error) {
        console.log(error);
        return res.sendStatus(500);
    }
  });

// get individual photo
router.get("/:id", async (req, res) => {
    try {
        // console.log("I'm here")
        let photo = await Photo.findOne({ 
            _id: req.params.id 
        });
        res.send(photo);
    } catch (error) {
        console.log(error);
        res.sendStatus(500);
    }
})

and my server.js:

const express = require('express');
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

const mongoose = require('mongoose');

// connect to the database
mongoose.connect('mongodb://localhost:27017/photobomb', {
  useNewUrlParser: true
});

const cookieParser = require("cookie-parser");
app.use(cookieParser());

const users = require("./users.js");
app.use("/api/users", users.routes);

const photos = require("./photos.js");
app.use("/api/photos", photos.routes);

const comments = require("./comments.js");
app.use("/api/comments", comments.routes);

app.listen(4000, () => console.log('Server listening on port 4000!'));
teachMeSenpai
  • 226
  • 1
  • 10

1 Answers1

0

The cast error is pointing that you might be using a wrong parameter to find the data,From looking a the above code i reckon you are trying to retrieve all the photos of the queried user,If that is the case user schema must have photo key associated to photos collection with objectId's like shown below, hence you can query for the user and populate the images parameter,which would give list of images associated to the user .Look for collection association in mongoose with OBJECTID What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"? this link explains the error you got.hope its of some help to you

{
   "user":String,
   "images":["imgs":{
                "type":mongoose.Schema.Types.ObjectId,
                "ref":"Photos"  
               }]

}