在下面的Meteor服务器代码中,它会在编译时打印出从myCol
获得的颜色。但是mongo shell命令改变了颜色,再次触发代码,无法打印出新颜色。
如何修复以便console.log(color)
打印出“新”颜色? THX
///////sever/food.js
let Milk = function () {
let color = Meteor.myCol.findOne({food:'milk'}).color;
return function () {
console.log (color);
}
}
export const Food = {
milk: new Milk()
}
//////server/buy.js
import {Food} from './food';
Food.milk(); // expecting to get the color saved in the collection at the time of calling
答案 0 :(得分:0)
函数milk是一个局部变量,它返回一个打印颜色的函数。从buy.js调用milk函数时,您只调用日志,而不是再次从db中获取文档,因此它具有旧值。
如果您只想获得牛奶的颜色并记录下来,我会在food.js中写下这样的牛奶功能(ES6):
const milkColor = () => {
let milk = myCol.findOne({food: 'milk'});
const color = milk?milk.color:undefined;
console.log(color);
}
export const Food = {
milk: milkColor
}
然后,在buy.js:
import {Food} from './food';
Food.milkColor();