我正在使用 mongoosepre
鉤子findOneAndUpdate
。我瀏覽了檔案以更好地了解它的用法。我想password
在保存到資料庫之前更新該欄位。但是,我沒有得到想要的結果 - 沒有任何改變。findOneAndUpdate
使用pre 鉤子修改檔案中某個欄位的正確方法是什么?
實際檔案
{
_id: new ObjectId("622457f5555562da89b7a1dd"),
id: '5982ca552aeb2b12344eb6cd',
name: 'Test User',
configuration: [
{
email: '[email protected]',
password: 'p@ssw0rd',
_id: new ObjectId("9473l58f2ad34efb816963dd"),
},
{
email: '[email protected]',
password: 'trUstN0oNe',
_id: new ObjectId("8674884cec1877c59c8838e0")
}
],
__v: 0
}
所需檔案
{
_id: new ObjectId("622457f5555562da89b7a1dd"),
id: '5982ca552aeb2b12344eb6cd',
name: 'Test User',
configuration: [
{
email: '[email protected]',
password: '0f359740bd1cda994f8b55330c86d845',
_id: new ObjectId("9473l58f2ad34efb816963dd"),
},
{
email: '[email protected]',
password: '3dba7872281dfe3900672545356943ce',
_id: new ObjectId("8674884cec1877c59c8838e0")
}
],
__v: 0
}
代碼:
const UserSchema = new Schema({
id: {
type: String,
required: [true, "'id' value is required"]
},
name: {
type: String,
required: [true, "'name' value is required"]
},
configuration: [ConfigModel.schema]
});
const ConfigSchema = new Schema({
email: {
type: String,
required: [true, "Email is required"]
},
password: {
type: String,
required: [true, "Password is required"]
}
});
UserSchema.pre('findOneAndUpdate', async function(next) {
const docToUpdate = await this.model.findOne(this.getQuery());
docToUpdate.configuration.forEach((item,i) => {
docToUpdate.configuration[i].password = md5(item.password);
});
return next();
});
uj5u.com熱心網友回復:
更改檔案內的資訊后,您缺少.save()
檔案命令,因為您只使用findOne
const docToUpdate = await this.model.findOne(this.getQuery());
docToUpdate.botconfiguration.forEach((item,i) => {
docToUpdate.configuration[i].password = md5(item.password);
});
await docToUpdate.save() // <---- this line
您不需要updateMany()
這里,因為 ConfigSchema 嵌套在用戶集合中
uj5u.com熱心網友回復:
在 userModel 中,您從 ConfigModel 讀取配置,因此您必須修改配置模型而不是用戶模型,它只是從配置模型讀取和填充資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/503991.html
上一篇:MongoDB增量物件陣列