如何在Mongo/Mongoose Schema方法中清空数组属性?
在Mongoose Schema方法中清空数组的正确方式
你的问题出在Mongoose文档里的数组不是原生JavaScript数组,而是Mongoose封装的MongooseArray对象。直接用splice(0)或设置length=0的操作,不会触发Mongoose的变更追踪机制,所以这些修改不会被同步到数据库。
解决方法很简单,直接给数组赋值为空数组[],Mongoose会自动识别这个变更:
userSchema.methods.generatePasswordReset = function () { const user = this; user.resetPasswordToken = crypto.randomBytes(20).toString('hex'); user.resetPasswordExpires = new Date(new Date().getTime() + 60 * 60000); if (user.resetPasswordAttemptTimes.length > 3) { // 直接赋值为空数组,触发Mongoose变更追踪 user.resetPasswordAttemptTimes = []; } user.resetPasswordAttemptTimes.push(new Date().getTime()); };
另外,也可以用MongooseArray提供的set方法来清空:
user.resetPasswordAttemptTimes.set([]);
或者用pullAll方法移除所有元素:
user.resetPasswordAttemptTimes.pullAll(user.resetPasswordAttemptTimes);
核心原因是Mongoose需要明确感知到数组的修改,原生数组的某些底层操作(比如直接改length、splice的无参数调用)不会被Mongoose的变更检测捕获,而赋值操作或者调用Mongoose提供的数组方法,会自动标记该字段为已修改,后续保存文档时就能同步这些变化。
内容的提问来源于stack exchange,提问作者learncode
相关产品推荐
相关产品推荐

