📜  mongoose | findByIdAndRemove()函数(1)

📅  最后修改于: 2023-12-03 14:44:23.145000             🧑  作者: Mango

Mongoose | findByIdAndRemove() Function

Introduction

Mongoose is a powerful ODM (Object Data Modeling) library for MongoDB in Node.js. The findByIdAndRemove() function is one of the methods provided by the Mongoose library to remove a specific document from the MongoDB database by its _id field.

Syntax

The syntax of the findByIdAndRemove() function is:

Model.findByIdAndRemove(id, [options], [callback])
  • id - This parameter is required. It specifies the _id of the document to be removed.
  • options - This parameter is optional. It contains the options for the function, such as the projection, sort, and justOne options.
  • callback - This parameter is optional. It is the function that will be called when the operation completes. If not specified, the function will return a Query object.
Examples
Example 1: Removing a Document

The findByIdAndRemove() function can be used to remove a document based on its _id field, as shown below:

const Model = require('./model');

Model.findByIdAndRemove('60d288d7b5ab2c32004f6557', (err, doc) => {
  if (err) {
    console.error(err);
  } else {
    console.log(doc);
  }
});

In the above example, we remove a document with the _id value of '60d288d7b5ab2c32004f6557' from the database. The method takes two parameters: the id of the document to be removed and a callback function to be executed when the operation is complete. If an error occurs during the operation, the function logs the error to the console. If the operation is successful, the function logs the removed document to the console.

Example 2: Using Options to Remove a Single Document

The findByIdAndRemove() function can be used with options to remove only one document from the collection, as shown below:

const Model = require('./model');

Model.findByIdAndRemove(
  { _id: '60d288d7b5ab2c32004f6557' },
  { justOne: true },
  (err, doc) => {
    if (err) {
      console.error(err);
    } else {
      console.log(doc);
    }
  },
);

In the above example, we pass a second parameter to specify the option justOne: true. This option ensures that only one document is removed from the collection, even if multiple documents match the query.

Conclusion

The findByIdAndRemove() function is a useful method provided by the Mongoose library for removing a specific document from the MongoDB database based on its _id field. It is also possible to use options to remove only one document from the collection, as shown in the examples above.