[英]Mongoose not updating database with findByIdAndUpdate?
我正在嘗試通過 HTML 表單使用findByIdAndUpdate
更新我的數據庫,該表單適用於除嵌套數據之外的所有數據( ePIMS
、 codeVersion
和region
所有更新都沒有問題)。 當我執行console.log(req.body.environment.instance)
時,它會輸出我輸入的數據,就像它正確通過一樣,但由於某種原因,mongoDB 沒有更新信息。 誰能弄清楚我做錯了什么?
mongoose 架構:
var environmentSchema = new mongoose.Schema({
ePIMS: String,
codeVersion: String,
region: String,
/*instance and testEnv don't seem to update in the database*/
HCHC: {
instance: String,
testEnv: String
}
});
我用來更新的表格:
<form action="/environments/<%= environment._id %>?_method=PUT" method="POST">
<input class="form-control" type="text" name="environment[ePIMS]" placeholder="ePIMS" value="<%= environment.ePIMS %>" />
<input class="form-control" type="text" name="environment[region]" placeholder="Region" value="<%= environment.region %>" />
<input class="form-control" type="text" name="environment[instance]" placeholder="HCHC Instance" value="<%= environment.instance %>" />
<input class="form-control" type="text" name="environment[testEnv]" placeholder="Test Environment" value="<%= environment.testEnv %>" />
<button class="btn btn-primary">Submit</button>
</form>
編輯和更新路線:
//Edit environment route
router.get("/environments/:id/edit", function(req, res){
Environment.findById(req.params.id, function(err, foundEnvironment){
if(err){
res.redirect("/");
} else {
res.render("edit", {environment: foundEnvironment});
}
});
});
//Update environment route
router.put("/environments/:id", function(req, res){
Environment.findByIdAndUpdate(req.params.id, req.body.environment, function(err, updatedEnvironment){
if (err) {
res.redirect("/environments");
} else {
res.redirect("/environments");
//console.log(req.body.environment.instance)
}
});
});
更新:解決方案感謝 Nayan 的幫助!
我改變了更新路線,如下所示:
//Update environment route
router.put("/environments/:id", function(req, res){
var data = {
HCHC : {
instance: req.body.instance,
testEnv: req.body.testEnv
}
}
Environment.findByIdAndUpdate(req.params.id, {$set: data}, function(err, updatedEnvironment){
if (err) {
res.redirect("/environments");
} else {
res.redirect("/environments");
}
});
});
您正在發送不同的主體結構並直接在 findOneAndUpdate() 中設置它,因此它不起作用,結構不同。
您可以應用的可能解決方案是將請求的正文更改為如下所示:
"environment" : {
"ePIMS" : value,
"codeVersion" : value,
"region" : value,
"HCHC": {
"instance" : value,
"testEnv" : value
}
}
或者,如果需要,您可以將兩個事物實例和 testEnv 放在 HCHC 之外。
無論哪種方式,如果您直接在 function 中傳遞正文,請確保您具有相同的結構。
另一種解決方案
創建一個局部變量來修復結構並將其傳遞到 function 中,例如:
router.put("/environments/:id", function(req, res){ let body = req.body.environment let bodyData = { ePIMS: body.ePIMS, codeVersion: body.codeVersion, region: body.region, HCHC: { instance: body.instance, testEnv: body.testEnv } } Environment.findByIdAndUpdate(req.params.id, bodyData, function(err, updatedEnvironment){ if (err) { res.redirect("/environments"); } else { res.redirect("/environments"); //console.log(req.body.environment.instance) } }); });
這個解決方案對我有用:
router.patch('/tasks/:id', async (req,res)=>{
try{
const task= await Task.findByIdAndUpdate(req.params.id,req.body,{new:true,runValidators:true})
if(!task)
{
res.status(404).send()
}
res.send(task)
}
catch(e)
{
res.status(500).send()
}
})
但是,我的最終解決方案包括驗證是在不使用 findByIdAndUpdate 的情況下執行更新:
router.patch('/tasks/:id', async (req,res)=>{
//validate update operation
const updates=Object.keys(req.body)
const allowedUpdates= ['description','completed']
const isInvalidOperation= updates.every((update)=>allowedUpdates.includes(update))
if(!isInvalidOperation)
{
return res.status(400).send({error:'invalid updates'})
}
try{
const task= await Task.findById(req.params.id)
updates.forEach((update)=>task[update]=req.body[update])
await task.save()
if(!task)
{
res.status(404).send()
}
res.send(task)
}
catch(e)
{
res.status(500).send()
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.