node.jsmongodbasync-awaitmongodb-querymongoose-schema

How do I delete a document in mongoDB using mongoose in Node.js?


I want to delete a document from a collection in mongoDB. This is my schema:

const userSchema = new mongoose.Schema(
  {
    _id: {
      type: String,
      default: () => uuidv4().replace(/\-/g, ""),
    },
    firstName: String,
    lastName: String,
    type: String,
  },
  {
    timestamps: true, // timestamps = true will add 2 things to my schema: a createdAt and a updatedAt date value.
    collection: "users",
  }
);

This is my code so far. How do i delete a row using schema above. This is my code so far

userSchema.statics.deleteUserById = async function (id) {
  try {
    console.log(typeof(id));
    const result = await this.remove({ _id: id});
    
    return result;
  } catch (error) {
    console.log(error)
    throw error;
  }
}

I'm calling the function through an API. and this is the error it throws

TypeError: this.remove is not a function
    at userSchema.statics.deleteUserById (file:///E:/secure-mm/server/models/User.js:53:31)
    at onDeleteUserById (file:///E:/secure-mm/server/controllers/user.js:40:42)
    at Layer.handle [as handle_request] (E:\secure-mm\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\secure-mm\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (E:\secure-mm\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (E:\secure-mm\node_modules\express\lib\router\layer.js:95:5)
    at E:\secure-mm\node_modules\express\lib\router\index.js:284:15
    at param (E:\secure-mm\node_modules\express\lib\router\index.js:365:14)
    at param (E:\secure-mm\node_modules\express\lib\router\index.js:376:14)
    at Function.process_params (E:\secure-mm\node_modules\express\lib\router\index.js:421:3)

What should i be using instead to delete a user y their id?


Solution

  • Mongoose has a straightforward method for deleting a document based on an id using your Model. It's the Model.findByIdAndDelete() as per the docs. In your case you can create a model from your schema like this:

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

    then delete like this:

    const result = await User.findByIdAndDelete(id);
    

    There are other ways of deleting documents in Mongoose. You can research them here as you may find you need a different approach as your application grows.

    As an aside, you don't need to define _id in your Schema.

    By default, Mongoose adds an _id property to your schemas. When you create a new document with the automatically added _id property, Mongoose creates a new _id of type ObjectId to your document.