我有一个叫做agent的猫鼬收藏。我可以使用mongodb控制台查看更新的数据。但是无法使用$ .ajax或$ .get
获取更新的数据我是nodejs和mongoose的新手。我更新的数据正在mongodb数据库上更新,但即使刷新后也不会在客户端上更新。
将更新后的集合发送到客户端的路由
router.get('/:function', function(req, res) {
if (req.params.function === 'getWeeklyTarget') {
helper.getWeeklyTarget().then(values => {
res.send(values);
})
}
})
getWeeklyTarget函数
function getWeeklyTarget() {
return new Promise((resolve, reject) => {
// Find Current Week
let this_month = `${moment().format('MMMM')} ${moment().format('YYYY')}`;
let this_week;
let team_targets = [];
Month.find({name: this_month})
.then(foundMonth => {
foundMonth.forEach(month => {
if (month.name === this_month) {
this_week = month.current_week;
}
findTeams.then(foundTeams => {
let this_week_target = [];
foundTeams.forEach(team => {
let counter = 0;
let another_counter = 0;
team.members.forEach(agent => {
if (this_week === 'first_week') {
counter += agent.weekly_target.first_week
another_counter += agent.total_sales
}else if (this_week === 'second_week') {
counter += agent.weekly_target.second_week
another_counter += agent.total_sales
}else if (this_week === 'third_week') {
counter += agent.weekly_target.third_week
another_counter += agent.total_sales
} else if (this_week === 'fourth_week') {
counter += agent.weekly_target.fourth_week
another_counter += agent.total_sales
}
})
this_week_target.push({
name: team.name,
target: counter,
achieved: another_counter
})
})
resolve(this_week_target);
})
})
})
})
}
更新收藏集后,我想将更新的数据提取到客户端
答案 0 :(得分:0)
似乎resolve()
方法被调用了一次以上,因为它在forEach
循环中被调用了。请尝试在this_week_target
循环之外声明forEach
,并在forEach循环之外也调用resolve()
。像这样
function getWeeklyTarget() {
return new Promise((resolve, reject) => {
// Find Current Week
let this_month = `${moment().format('MMMM')} ${moment().format('YYYY')}`;
let this_week;
let team_targets = [];
Month.find({name: this_month})
.then(foundMonth => {
let this_week_target = [];
foundMonth.forEach(month => {
if (month.name === this_month) {
this_week = month.current_week;
}
findTeams.then(foundTeams => {
foundTeams.forEach(team => {
let counter = 0;
let another_counter = 0;
team.members.forEach(agent => {
if (this_week === 'first_week') {
counter += agent.weekly_target.first_week
another_counter += agent.total_sales
}else if (this_week === 'second_week') {
counter += agent.weekly_target.second_week
another_counter += agent.total_sales
}else if (this_week === 'third_week') {
counter += agent.weekly_target.third_week
another_counter += agent.total_sales
} else if (this_week === 'fourth_week') {
counter += agent.weekly_target.fourth_week
another_counter += agent.total_sales
}
})
this_week_target.push({
name: team.name,
target: counter,
achieved: another_counter
})
})
})
})
resolve(this_week_target);
})
})
}