如何在Node.js中使用Mongoose删除MongoDB中的用户文档?
问题:Mongoose删除文档报错TypeError: this.remove is not a function?
我想删除MongoDB集合中的文档,我的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", } );
我写了下面的静态方法,但调用API时抛出错误:
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; } }
错误信息:
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删除用户?
解决方案
错误原因
this.remove()是Mongoose v5.x及更早版本的方法,在v6.x及以后的版本中已被废弃,无法再通过模型直接调用该方法。
替代方案
方案1:使用deleteOne()(推荐)
适合仅需确认删除结果的场景,返回包含删除计数的对象:
userSchema.statics.deleteUserById = async function (id) { try { console.log(typeof(id)); const result = await this.deleteOne({ _id: id }); return result; } catch (error) { console.log(error) throw error; } }
方案2:使用findByIdAndDelete()
如果需要获取被删除的文档数据,用这个方法会直接返回删除前的用户对象:
userSchema.statics.deleteUserById = async function (id) { try { console.log(typeof(id)); const deletedUser = await this.findByIdAndDelete(id); return deletedUser; } catch (error) { console.log(error) throw error; } }
补充说明
deleteOne()返回结果示例:{ acknowledged: true, deletedCount: 1 },其中deletedCount为成功删除的文档数量。findByIdAndDelete()会返回匹配到的并被删除的文档,如果没有找到对应ID的用户,会返回null。
内容的提问来源于stack exchange,提问作者Siddharth Sagar
相关产品推荐
相关产品推荐

