DevStarlight DevStarlight - 2 months ago 40
Javascript Question

unexpected result for a promise

I'm trying to filter a populated element so depending of a

true || false
, then I remove some fields or not.

That said, I'm literally copying the code of my endpoint with the unexpected response:

router.get('/endpoint', tokenAuth, function (req, res) {
var json_allData;
.then(function (data) {
json_allData = data;
return Model.filterAnonymous(data.subdocument);
.then(function (data) { // << Data here is a subdocument filtered as expected
res.status(200).json({ data: json_allData }); // << WTF??? data has been filtered in the json_allData but I'm not doing anything!
.catch(function (error) {
res.status(400).json({ msg: error });

Hope someone can throw some light here.

Thanks in advice.


When you do

json_allData = data;

You make json_allData point to the same memory as data. This means both variable reference the same object.

Now when you do


That changes the subdocument property which is part of the object data is referencing and that is still the same object json_allData is referencing.