2017-02-09 111 views
0

我正在處理我的項目的用戶帳戶部分。我成功地完成了GET,POST和DELETE方法,現在我錯過了PUT。貓鼬更新功能不起作用

當用戶提交更新用戶表單,該req.body會是這樣的

{ user: 
    { firstName: 'asas', 
    lastName: 'assa', 
    studentId: '1234', 
    email: '[email protected]', 
    password: '123' 
    } 
} 

我的模式是這樣的:

const userSchema = new Schema({ 
    cuid: { type: 'String', required: true }, 
    firstName: { type: 'String', required: true }, 
    lastName: { type: 'String', required: true }, 
    studentId: { type: 'Number', required: true }, 
    password: { type: 'String', required: true }, 
    email: { type: 'String', required: true }, 
    dateAdded: { type: 'Date', default: Date.now, required: true }, 
    lastLogin: { type: 'Date', default: null, required: false }, 
}); 

最後我更新功能看起來是這樣的。

export function updateUser(req, res) { 

    console.log(req.body) 
    firstName = sanitizeHtml(req.body.user.firstName); 
    lastName = sanitizeHtml(req.body.user.lastName); 
    studentId = sanitizeHtml(req.body.user.studentId); 
    email = sanitizeHtml(req.body.user.email); 
    password = sha512(req.body.user.password).toString('hex'); 

    let update = { firstName, lastName, studentId, email, password }; 

    User.findOneAndUpdate(req.params.cuid,update,function(err,updated){ 
    if(error){ 
     return res.status(500).send(err); 
    }else{ 
     return res.json({ user: updated }); 
    } 
    }); 
} 

我不明白爲什麼我的put方法不工作,也許第二雙眼睛可以看到缺陷。

回答

0

你很近。問題是你沒有正確傳遞ID。 MongoDB正在尋找一個對象形式的標識符。你寫的:

User.findOneAndUpdate(req.params.cuid,update,function(err,updated){ 

你需要做的是獨立的參數爲單獨的對象:

User.findOneAndUpdate({ _id: req.params.cuid }, { $set: update }, function(err, updated) { 

此外,你需要使用$set,否則你會覆蓋整個對象。 $set告訴Mongo只更新通過update對象指定的字段,您在上面定義了幾行。

0

您沒有使用findOneAndUpdate的正確結構。首先你已經定義了,在哪個基礎上搜索id。

export function updateUser(req, res) { 

    console.log(req.body) 
    firstName = sanitizeHtml(req.body.user.firstName); 
    lastName = sanitizeHtml(req.body.user.lastName); 
    studentId = sanitizeHtml(req.body.user.studentId); 
    email = sanitizeHtml(req.body.user.email); 
    password = sha512(req.body.user.password).toString('hex'); 

    let update = { firstName, lastName, studentId, email, password }; 

User.findOneAndUpdate({_id: req.params.cuid}, {$set: updated}, function (err, user) {//correct structure 
    if(error){ 
     return res.status(500).send(err); 
    }else{ 
     return res.json({ user: updated }); 
    } 
    }); 
} 

希望這有助於。

+0

這是適合你嗎? –

0

我相信你需要使更新參數作爲一個對象。

第一個參數是查詢對象。例如{firstName:「whatever」}。 第二個參數包含更新。

舉個例子,如果你要更新的用戶的姓氏,並通過名稱搜索,你應該有類似

findOneAndUpdate({firstName:req.body.firstName},{lastName:req.body.lastName},function...}) 

我相信你正試圖通過ID進行搜索,所以你應該把類似

findOneAndUpdate({cuid:req.body.cuid},{$set:{firstName:req.body.firstName,studentId:req.body.studentId...}),function...}) 

我希望我的回答是對你有幫助。