所以我有一個主 mongoDB 物件,其中嵌套了多個檔案。我想訪問陣列中的特定檔案并修改其中一個值。這是我的檔案設定
const sectionSchema = new mongoose.Schema({
name: String,
items: [itemSchema],
currentAmount: {
type: mongoose.Decimal128,
default: 0
},
limitAmount: {
type: mongoose.Decimal128,
required: true
},
isActive: {
type: Boolean,
default: 0
}
});
const Section = new mongoose.model("Section", sectionSchema);
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique:true
},
email: {
type: String,
lowercase: true,
trim:true,
required: true,
unique: true
},
password: {
type: String,
required: true
},
sections: [sectionSchema]
});
const User = new mongoose.model("User", userSchema);
我添加了一些虛擬值來填充資料庫,包括其他 testSection 和 testItems。
const testSection2 = new Section({
name: "Vacation",
items: [testItem3,testItem4],
currentAmount: 0,
limitAmount: 800,
isActive: 1
});
const testUser = new User({
username: "wavey123",
email: "[email protected]",
password: "wvy123",
sections: [testSection1,testSection2]
});
我嘗試了 .findOneAndUpdate 方法的不同迭代,但沒有成功,例如:
app.post("/sSelect", function(req,res){
const selectedSection = req.body.sectionName;
User.findOneAndUpdate({sections: {$elemMatch: {isActive: 1}}},{sections: {isActive: 0}},{new: true}, function(err, aSection){
if (err){
console.log(err)
}
console.log(aSection);
})
User.findOneAndUpdate(({sections: {$elemMatch: {name: selectedSection}}}),{$set: {sections: {isActive: 1}}},{new: true}, function(err, aSection){
if (aSection){
res.redirect("/");
}
})
我最終得到的基本檔案如下所示:
[
{
_id: ObjectId("629a971bb8a72843a07df0fd"),
username: 'wavey123',
email: '[email protected]',
password: 'wvy123',
sections: [
{
currentAmount: Decimal128("0"),
isActive: false,
_id: ObjectId("629a9756792a3b21872c329f"),
items: []
}
],
__v: 0
}
]
這發生在第一個 .findOneAndUpdate 之后。似乎無法理解它。
uj5u.com熱心網友回復:
所以我只是廢棄了整個 .findOneAndUpdate 并使用 JS 來查找 isActive 鍵并像這樣操作它:
app.post("/sSelect", function(req,res){
const selectedSection = req.body.sectionName;
User.findOne({}, function(err, aSection){
aSection.sections.forEach(function(section){
if(section.isActive === true){
section.isActive = false;
console.log(section.isActive)
aSection.save();
}
})
});
User.findOne({}, function(err, aSection){
aSection.sections.forEach(function(section){
if(section.name === selectedSection){
section.isActive = true;
console.log(section.name,section.isActive)
aSection.save();
}
})
});
res.redirect("/");
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/486853.html
