我想从 mongoDB 的集合中删除文档。这是我的架构:
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",
}
);
这是我到目前为止的代码。如何使用上面的架构删除一行。这是我到目前为止的代码
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;
}
}
我通过 API 调用该函数。这就是它抛出的错误
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)
我应该使用什么来删除用户及其 ID?
Mongoose 有一种简单的方法,可以使用模型根据 id 删除文档。这是
docs中的
Model.findByIdAndDelete()
a。根据您的情况,您可以更改此设置:
const result = await this.remove({ _id: id});
对此:
const result = await this.findByIdAndDelete(id);
Mongoose 中还有其他删除文档的方法。您可以在此处研究它们,因为您可能会发现随着应用程序的增长,您需要不同的方法。