![](/img/trans.png)
[英]JavaScript - Express - MongoDb - Mongoose findOneAndUpdate is returning undefined
[英]findOneAndUpdate mongoDB not returning properly
我試圖將用戶的選擇作為字符串推送到他們的選擇數組並返回更新的文檔。
路由和函數成功運行,但是它返回帶有空選項數組的用戶。 我相信問題出在控制器功能的某個地方,但我無法弄清楚。 任何幫助是極大的贊賞!
為了提供幫助,這里是我的控制台的屏幕截圖,您可以在其中看到一個空的選擇數組被返回。 這是我的 console.log 的圖像
這是我調用函數的地方
handleAnswerInput = (question) => {
let answerTextSelected = question.Text;
let answerTypeSelected = question.Type;
let usersName = this.state.user._id
this.setState({
count: this.state.count + 1
})
saveUserandScore(usersName, answerTextSelected)
.then(
this.loadQuestion(this.state.count)
)
console.log(answerTextSelected)
console.log(answerTypeSelected)
};
這是控制器功能(根據建議更新)
const saveUserAndTheirScore = (req, res) => {
let filter = { _id: req.params.id }
// let update = { choices: req.params.answer] }
console.log(req.params.id)
console.log(req.params.answer)
User.update(
{ filter },
{
$push: { choices: req.params.answer }
},
{
returnOriginal: false,
},
)
.then(dbData => res.json(dbData))
.catch(err => {
console.log(err);
res.json(err);
});
};
這是 axios 調用
export const saveUserandScore = (id, answer) => {
return axios.post(`/api/user/${id}/${answer}`);
};
findOneAndUpdate(filter, update, options, callback)
有一個returnOriginal
選項,如果設置為true
(這是默認值),它將在更新之前返回文檔。 在您的情況下,您可能希望將其設置為false
[1]。
不幸的是,mongoose 的相應選項被命名為new
[2]。
[1] https://mongodb.github.io/node-mongodb-native/3.4/api/Collection.html#findOneAndUpdate
[2] https://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate
您需要更改用戶架構,因為您可能已將選擇類型定義為字符串。 它必須是一個數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.