无法在找到一个后更新架构中的架构



嘿伙计们,我正在尝试更新我的 FoodSchema,它在我的 POST 请求中的餐厅架构中 这是我的架构:

//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但我不确定这是否是这里最好的做法。有什么想法吗?

好吧,我解决了它:这不是最有效的方法,但尽管如此,它就在这里。我使用了塔尔哈的保存方法。

//votes POST route
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
{
//Parse the food string data.
var newFoodString = toTitleCase(req.body.food); 
//If there's no food data, initialize it. 
if(restdata.favoriteFoods.length===0)
{
restdata.favoriteFoods.push({nameOfFood:newFoodString,numOfVotes:1});
restdata.save().then(function(data){
console.log(data);
});
}
else
{
var flag = false;
for(var count = 0; count < restdata.favoriteFoods.length; count++)
{
//If you can find the food. Just add a vote.
if(restdata.favoriteFoods[count].nameOfFood==newFoodString)
{
flag = true;
restdata.favoriteFoods[count].numOfVotes++;
restdata.save().then(function(data){
console.log(data);
});
}
}
//Otherwise push it as a new food.
if(!flag)
{
restdata.favoriteFoods.push({nameOfFood:newFoodString,numOfVotes:1});
restdata.save().then(function(data){
console.log(data);
});
}
}
}
});
});
return router;
}

最新更新