Home > front end >  Mongoose query that limit the collections to collections those belong to the logged in user or that
Mongoose query that limit the collections to collections those belong to the logged in user or that

Time:10-02

I am working on a web app, where every user should see their own collections. So if i log in as user1, it should show user1's collections and if i log in as user2 it should show only user2's collections.

Right now, no matter which user i log in, and get collections route it does show all collections. I am using expressjs and mongoose.I need help how to query from db to get specific data which is belong to logged in user

Collections route

collectionRouter.get("/", async(req,res,next)=> {
    try {   
        const collections= await CollectionModel.find()
        res.send(collections)
    } catch (error) {
        next(error)
    }
})

collectionRouter.post("/", async(req,res,next)=> {
    try {
        const collection = new CollectionModel(req.body)
        const {_id} = await collection.save()
        res.status(201).send({_id})
    } catch (error) {
        next(error)
    }
})

User login route

userRouter.post("/login", async (req, res, next) => {
  try {
    const { email, password } = req.body;
    if (!(email && password))
      res.status(204).send({ msg: "All fields are required!" });
    const user = await UsersModel.checkCredentials(email, password);
    if (user) {
      const accessToken = await JWTAuthenticate(user);
      res.status(200).send({ accessToken });
    } else {
      next(
        createHttpError(401, "Credentials are not ok. User does not exist!")
      );
    }
  } catch (error) {
    next(error);
  }
});

Collections schema

const { Schema, model } = mongoose;
const collectionSchema = new Schema(
  {
    name: { type: String },
    description: { type: String },
    topic: { type: String },
    comments: [
      {
        commentArea: { type: String, required: true },
        commentedDate: `enter code here`{ type: Date },
      },
    ],
    users: [{ type: Schema.Types.ObjectId, ref: "User" }],
    likes:[{type:Schema.Types.ObjectId, ref:"Like"}],
  },
  { timestamps: true }
);
export default model("Collection", collectionSchema);

CodePudding user response:

Firstly, you need to protect the endpoint so you can get the logged in user id. Then, you will have to query collections by current logged in user's _id to get specific data related to the user.

Example usage of an auth middleware:

collectionRouter.get("/", yourAuthMiddleware(), async(req,res,next)=> {
    try {   
        // method to obtain user id will depend on authentication middleware
        const user = req.user.id
        const collections= await CollectionModel.find({users: user}) // filtered by user _id
        res.send(collections)
    } catch (error) {
        next(error)
    }
})
  • Related