0
嗨,我試圖更新我的FoodSchema這是我的POST請求裏面這裏我的店模式中是我的架構:無法findOne後更新架構內的架構
//Create food schema
const FoodSchema = new Schema ({
nameOfFood: String,
numOfVotes: Number,
});
//Create restaurant schema
const RestaurantSchema = new Schema ({
nameOfRest: String,
favoriteFoods:[FoodSchema],
});
我試圖更新食品在else語句中發現它找到餐廳,並且我能夠訪問.then
方法內的restdata中的數據時,它不會推送新餐館。我試圖完成的目標是,如果它找到了餐廳,我更新它的食品模式。
router.post('/votes', function(req,res)
{
//Parse the data.
var newString = toTitleCase(req.body.restaurant);
Restaurant.findOne({nameOfRest:newString}).then(function(restdata)
{
//If can't find restaurant, redirect to vote page again.
if(!restdata)
{
console.log("Undefined");
res.redirect('/votes');
}
//Restaurant is found
//If the food can't be found create and push a new array with one vote.
//If you can find the food, then just update and add a vote.
else
{
if(restdata.favoriteFoods.length==0)
{
restdata.favoriteFoods.push({nameOfFood:req.body.food,numOfVotes:1});
}
else
{
restdata.favoriteFoods.numOfVotes++;
}
}
});
});
更進一步我測試這個代碼:
restdata.favoriteFoods.push({nameOfFood:req.body.food,numOfVotes:1});
然而,當我試圖推動它,這是行不通的。我正在考慮使用findOneAndUpdate
,但我不確定這是否是最好的選擇。有任何想法嗎?
將數據插入'restdata'之後,您是否保存它? –
不,我不需要,因爲它已經在我的數據庫中。 –
您不會在數據庫中找到推送的文檔。那就是問題所在? –