Closed Josema closed 9 years ago
This solution solve the problem. But i would like to know if exists a solution using the architecture of orm2.
for (var i = 0; i < list.length; ++i) {
Player.find({ name: list[i].name}, (function(i) {
return function(err, item) {
if (item.name == list[i].name)
// more code
}
})(i));
}
Another more common form:
for (var i = 0; i < list.length; i++) {
(function (list_item) {
Player.find({ name: list_item.name }, function (err, item) {
if (item.name == list_item.name) {
// ....
}
});
})(list[i]);
}
Please provide a more real example because the if
condition makes no sense in this example and chaining might be a solution depending on the real example.
I just want to check if exists the item, if exists update it, if not create it.
Then just check err
(there's a not found error).
for (var i = 0; i < list.length; i++) {
Player.find({ name: list[i].name }, function (err, item) {
if (err) {
// create it..
}
});
}
To create it, i have to be able to access to the correct item of list. Thats why i have to pass the i parameter or the list item.
Anyway. Are u sure that err is only defined when already exists? Mysql can throw errors for other reasons i guess.
I might be confusing (I think the "not found" error is only for .get
). In your case, if name
is a unique column (or index..) you can just check if item
(which actually should be an Array) is empty or not.
Player.find
should always get you an Array, even if the results are one element.
As an alternative:
for (var i = 0; i < list.length; i++) {
Player.get({ name: list[i].name }, function (err, player) {
if (err && err.code == orm. ErrorCodes.NOT_FOUND) {
// create it..
}
});
}
In this case you could just check if player
is undefined
. Here is the code.
I am not able to pass the variable
i
.In the example above the value of
i
its the same of list.length and i am not able to access to the correct itme of list. What is the best way to solve this problem?