我試圖更新具有陣列的檔案的一部分。我聽說這是 mongoose 的一大禁忌,但我不知道如何強制它更新陣列。它在代碼中正確執行(例如,它更新本地獲取的檔案中的值),但是當我嘗試通過 保存它時await mongoUser.save(),它沒有在 mongo 中更新。
這是我的架構代碼
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
id: { type: String, required: true},
socialCreditScore: { type: Number, required: true, default: 1000 },
/* A : 1050
// A: 960 - 1050
// B: 850 - 959
// C: 600 - 849
/ D: 0 - 599 */
isStaff: { type: Boolean, required: true, default: false },
blacklisted: { type: Boolean, required: true, default: false},
guildScores: { type: Array, required: true, strict: false } ,
notifyChange: { type: Boolean, required: true, default: false }
}, {strict: false, timestamps: true })
module.exports = mongoose.model('User', UserSchema);
這是本地更新檔案的示例
{
_id: new ObjectId("61c1218ae82898e9cd7af768"),
id: '945914953495034509',
socialCreditScore: 2100,
isStaff: false,
blacklisted: false,
# Previously: guildScores: [ { id: "...", laborScore: 0 } ]
guildScores: [ { id: '04503405340534545', laborScore: 2000 } ],
notifyChange: false,
createdAt: 2021-12-21T00:36:26.871Z,
updatedAt: 2021-12-21T00:50:27.286Z,
__v: 0
}
更新用戶的代碼
const data = await User.find({ id: message.author.id });
const mongoUser = data[0];
// ...
mongoUser.socialCreditScore = socCreditBoost;
const guildScoreData = mongoUser.guildScores.find(guild => guild.id === message.guild.id);
// { id, laborScore }
guildScoreData.laborScore = salary;
console.log(mongoUser);
await mongoUser.save();
編輯:我注意到每次嘗試更新 socialCreditScore 值時都會正確更新,但是 guildScore 沒有。
uj5u.com熱心網友回復:
我相信陣列沒有被保存的原因是因為guildScores欄位的型別是Array. 在架構型別的檔案中Array,它說指定 justArray等效于Mixed. 架構型別的檔案Mixed指出:
由于 Mixed 是無模式型別,您可以將值更改為您喜歡的任何其他值,但 Mongoose 無法自動檢測和保存這些更改。要告訴 Mongoose Mixed 型別的值已更改,您需要呼叫 doc.markModified(path),將路徑傳遞給您剛剛更改的 Mixed 型別。
為了避免這些副作用,可以改用子檔案路徑。
person.anything = { x: [3, 4, { y: "changed" }] }; person.markModified('anything'); person.save(); // Mongoose will save changes to `anything`.
在你的情況下,mongoUser.markModified('guildScores')可能會成功。
或者,您也可以使用 Mongoose 的findOneAndUpdate方法在一次操作中查找和更新檔案(我假設您每個 id 只有一個檔案)。它可能看起來像這樣:
await User.findOneAndUpdate(
{ id: message.author.id, 'guildScores.id': message.guild.id },
{ $inc: { socialCreditScore: socCreditBoost, "guildScores.$.laborScore": salary }}
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/388217.html
上一篇:8位非重復數字的正則運算式
