Reputation: 39
first i make a '/init' request and the response is {"x":50}
,
then i make a '/user' request and the response is {"x":50,"data":"jack"}
. No problem so far, but if i make an init request again it makes a {"x":50,"data":"jack"}
response again, how is this possible?
var resp.success = {"x":50}
exports.init = function (req, res) {
res.json(resp.success)
};
exports.user = function (req, res) {
User.findOne({_id: "1234"}).exec(function (err, user) {
var response = resp.success;
response.data = user.name;
res.json(response);
});
};
Upvotes: 0
Views: 132
Reputation: 21
Because you've defined var resp.success = {"x":50} in a scope outside the @init and @user methods, when you modify/read the resp.success from within those methods, they are accessing a single shared object instance of resp.success. You can fix this by defining resp.success independently inside the @init method and @user:
exports.init = function (req, res) {
var resp.success = {"x":50}
res.json(resp.success)
};
exports.user = function (req, res) {
var resp.success = {"x":50}
User.findOne({_id: "1234"}).exec(function (err, user) {
var response = resp.success;
response.data = user.name;
res.json(response);
});
};
If you use the underscoreJS library, you could also do something like this:
var resp.success = {"x":50}
exports.init = function (req, res) {
var successResponseForThisRequest = _.clone(res.success);
res.json(resp.success)
};
exports.user = function (req, res) {
User.findOne({_id: "1234"}).exec(function (err, user) {
var successResponseForThisRequest = _.clone(res.success);
response.data = user.name;
res.json(response);
});
};
Upvotes: 2