Item.filter is not a function

Issue

Hi everyone I am making a route to get the items that are created by the logged-in user but when I use the .filter function I get an error. Not sure why I am getting this error. I have made other apps before doing the same thing and never got an error

Item.filter is not a function

The my-items route

const requireAuth = require("../middleware/requireAuth");
const express = require("express");
const mongoose = require("mongoose");
const Item = mongoose.model("Item");

router.get("/my-items", requireAuth, async (req, res) => {
  try {
    const items = Item.filter((item) => item.userId === req.user.userId);
    res.send(items);
  } catch (err) {
    console.log(err);
  }
});

Item Schema

const mongoose = require("mongoose");

const itemSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  phone: {
    type: mongoose.Schema.Types.String,
    ref: "User",
  },
  email: {
    type: mongoose.Schema.Types.String,
    ref: "User",
  },
  seller: {
    type: mongoose.Schema.Types.String,
    ref: "User",
  },
  title: {
    type: String,
    required: true,
  },
  category: {
    type: String,
    required: true,
  },
  detail: {
    type: String,
    requiredL: true,
  },
  condition: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
});

mongoose.model("Item", itemSchema);

Solution

const items = await Item.find(({userId:req.user.userId}).lean();

it should return exact items from db that you want you can use more query if you need.

Answered By – MD. Sani Mia

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.