Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with User.remove, it says that it is not a function

I'm trying to post users on /user with express.Router() But it says that await User.remove is not a function. Maybe i need to import some more features? Here is code

import express from "express";
import User from "./Models/UserModel.js";
import users from "./data/users.js";
import Product from "./Models/ProductModel.js"


const ImportData = express.Router()

ImportData.post(
    "/user",
    async (req, res) => {
      await User.remove({});
      const importUser = await User.insertMany(users);
      res.send({ importUser });
    }
  );

ImportData.post("/products",async (req,res)=>{
    await Product.remove({});
    const importProducts = await Product.insertMany(products);
    res.send({ importProducts });
});

export default ImportData;

Here is error:

await User.remove({});
                 ^

TypeError: User.remove is not a function
    at file:///C:/react//frontend/Server/DataImport.js:12:18 

UserModel.js:

import mongoose from "mongoose";
import bcrypt from "bcryptjs";

const userSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    isAdmin: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  {
    timestamps: true,
  }
);

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

export default User;

I tried a lot, maybe here is another solving of this problem? Thank u in advance

like image 692
Sanchosmore Avatar asked Aug 23 '26 16:08

Sanchosmore


2 Answers

In new mongoose versions, document.remove() is deprecated. Replace remove() with deleteOne() or deleteMany().

Check the mongoose documentation's deprecation warning here.

like image 162
White Nuzzle Avatar answered Aug 26 '26 04:08

White Nuzzle


The object you are calling remove() on is a Model. Looking at its documentation, there indeed is no remove function; the only function whose name hints at similar behavior I can find is the deleteOne() and deleteMany() function found in the documentation.

The remove function is part of a Schema, as seen here in the documentation. In your code, a Schema is only used in the UserModel.js file, to create the Model.

like image 30
LeMoonStar Avatar answered Aug 26 '26 05:08

LeMoonStar