Locals Variable Not Updating Correctly
I am displaying a bunch of pages from a collection, so to have them available in my view I initialize a global locals variable in app.js like so: Page.find({}).sort({ sorting : 1})
Solution 1:
Okey, then I understood your problem.
The problem is than your page.save
take more time than your for
So after your find will get almost the same result than before.
Where do you use it (for
) ? in a special route ?
Simple Asynchronous javascript problems ;)
```
function sortPages(ids, callback) {
var total = 0;
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
count++;
(function(count) {
Page.findById(id, function (err, page) {
page.sorting = count;
page.save(function (err) {
++total;
if (err)
console.log(err);
if (total >= ids.length) {
callback('done');
}
});
});
})(count);
}
}
sortPages(ids, function () {
Page.find({}).sort({sorting: 1}).exec(function (err, pages) {
if (err) {
console.log(err);
} else {
req.app.locals.pages = pages;
}
});
});
```
Post a Comment for "Locals Variable Not Updating Correctly"