0

please take a look and let me know why the loop's output is not correct?

Basically I am looping through the friendId array of a user and through the user results for a search and seeing if they match up, depending on the match it should return true or false.

Here is my code for the loop:

User.findById(req.signedCookies.userid, function(err, signedInUser) {
    //console.log(JSON.stringify(signedInUser.friendRequest));
    for (var x = 0; x < users.length; x++) {
        users[x].isFriend = false;
        //console.log(users[x].lastName);
        for (var i = 0; i < signedInUser.friendRequest.length; i++) {
            //  console.log(users[x]._id + ' - ' + signedInUser.friendRequest[i].friendId);
            //console.log(users[x].isFriend);
            if (users[x]._id === signedInUser.friendRequest[i].friendId) {
                users[x].isFriend = true;
                console.log('test');
                break;
            }
        }
    }
    res.render('searchResults', {
        title: 'Weblio',
        userAdded: users
    });
});

Output of console.log:

 [{"friendId":"51ee2017c2023cc816000002","read":0,"date_requested":"2013-07-23T06
:29:39.021Z"},{"friendId":"51ee203cc2023cc816000003","read":0,"date_requested":"
2013-07-23T06:42:37.872Z"}]
Jones
51ee2017c2023cc816000002 - 51ee2017c2023cc816000002
false
51ee2017c2023cc816000002 - 51ee203cc2023cc816000003
false
Macks
51ee203cc2023cc816000003 - 51ee2017c2023cc816000002
false
51ee203cc2023cc816000003 - 51ee203cc2023cc816000003
false

The signed in user is John Smith and he searched for Jake

Users: John Smith id ends in 01 Jake Jones ends in 02 Jake Macks ends in 03

Where in fact Jake Macks is in the friendId

console.log('test');

is not being outputed, so I am assuming it is not even going into the if statement of the nested loop

Here is the inputs for these console logs I called right before the console log you moved:

console.log(users);
console.log(signedInUser);
console.log(users[x].isFriend);

The results are:

[ { firstName: 'Jake',
    lastName: 'Jones',
    email: 'test2@gmail.com',
    password: '$2a$10$3ndDWiqOsyN.WN19fKJqq.xiC0B9da7QKTL74995zCT8vHrClo2uW',
    phone: 98439843943,
    birthday: Mon Jun 04 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
    _id: 51ee2017c2023cc816000002,
    __v: 0,
    friend: [],
    friendRequest: [] },
  { firstName: 'Jake',
    lastName: 'Macks',
    email: 'test3@gmail.com',
    password: '$2a$10$XTsGrWmmOH/3O3eNwrNK2u.XOwl5cPPGyKrzgU0RMROcGTtU1LkDK',
    phone: 49372432922,
    birthday: Mon Jun 04 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
    _id: 51ee203cc2023cc816000003,
    __v: 0,
    friend: [],
    friendRequest: [] } ]
{ __v: 0,
  _id: 51ee1ddbc2023cc816000001,
  birthday: Mon Aug 06 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
  email: 'test1@gmail.com',
  firstName: 'John',
  lastName: 'Smith',
  password: '$2a$10$w6jTLvW.gUW5tY59/2/vIu8XPVsOe/NTr3e.Qc0WvVKIG8/MwSDW.',
  phone: 1122334422,
  friend: [],
  friendRequest:
   [ { date_requested: Tue Jul 23 2013 02:29:39 GMT-0400 (Eastern Daylight Time)
,
       read: 0,
       friendId: 51ee2017c2023cc816000002 },
     { date_requested: Tue Jul 23 2013 02:42:37 GMT-0400 (Eastern Daylight Time)
,
       read: 0,
       friendId: 51ee203cc2023cc816000003 } ] }
false
[ { firstName: 'Jake',
    lastName: 'Jones',
    email: 'test2@gmail.com',
    password: '$2a$10$3ndDWiqOsyN.WN19fKJqq.xiC0B9da7QKTL74995zCT8vHrClo2uW',
    phone: 98439843943,
    birthday: Mon Jun 04 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
    _id: 51ee2017c2023cc816000002,
    __v: 0,
    friend: [],
    friendRequest: [] },
  { firstName: 'Jake',
    lastName: 'Macks',
    email: 'test3@gmail.com',
    password: '$2a$10$XTsGrWmmOH/3O3eNwrNK2u.XOwl5cPPGyKrzgU0RMROcGTtU1LkDK',
    phone: 49372432922,
    birthday: Mon Jun 04 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
    _id: 51ee203cc2023cc816000003,
    __v: 0,
    friend: [],
    friendRequest: [] } ]
{ __v: 0,
  _id: 51ee1ddbc2023cc816000001,
  birthday: Mon Aug 06 2012 20:00:00 GMT-0400 (Eastern Daylight Time),
  email: 'test1@gmail.com',
  firstName: 'John',
  lastName: 'Smith',
  password: '$2a$10$w6jTLvW.gUW5tY59/2/vIu8XPVsOe/NTr3e.Qc0WvVKIG8/MwSDW.',
  phone: 1122334422,
  friend: [],
  friendRequest:
   [ { date_requested: Tue Jul 23 2013 02:29:39 GMT-0400 (Eastern Daylight Time)
,
       read: 0,
       friendId: 51ee2017c2023cc816000002 },
     { date_requested: Tue Jul 23 2013 02:42:37 GMT-0400 (Eastern Daylight Time)
,
       read: 0,
       friendId: 51ee203cc2023cc816000003 } ] }
false
dc5
  • 12,341
  • 2
  • 35
  • 47
Lion789
  • 4,402
  • 12
  • 58
  • 96
  • 1
    What is the output, and what output do you expect? – Dan455 Jul 23 '13 at 16:03
  • I added the output which returns as false 2 times for each user in the search result... – Lion789 Jul 23 '13 at 16:21
  • 2
    In the current post, your console.log statements are BEFORE the assignment. – Hector Correa Jul 23 '13 at 16:30
  • Just wondering, how are you getting that output if your console.log statements are commented out? – Dan455 Jul 23 '13 at 16:33
  • I uncommented them to see the result of it, so I can show the output, and currently the output is showing up as false, and the console.log('test'); is not being outputed, so I am assuming it is not even going into the if statement of the nested loop – Lion789 Jul 23 '13 at 16:35
  • 1
    The order of the output is very strange. Is that the exact order in which you see it? Or did you change it when you put it in your question? – Dan455 Jul 23 '13 at 16:45
  • +1 to Dan455. The log you posted cannot have been produced by the uncommented log statements, there would always be a boolean after the string. – Bergi Jul 23 '13 at 16:47
  • Sorry about that, I added the false in afterwards by accident, but that is the exact way it shows up. – Lion789 Jul 23 '13 at 16:52
  • Could you edit your question to include a sample of users? – dc5 Jul 23 '13 at 17:02
  • I added a sample of users in the bottom, basically there are 3 users in the db, John, and 2 others who firstName begins with Jake. A search result for Jake, while signed in as John should return two users with isFriend that is true or false. – Lion789 Jul 23 '13 at 17:06
  • 1
    That isn't descriptive enough, what is the output of `console.log(users)`? – Dan455 Jul 23 '13 at 17:14
  • Oh sorry, users returns the users found from the search result... so it returns the entire user's info (in this case it shows both Jake's and their respective information, name, email, pw, etc.) – Lion789 Jul 23 '13 at 17:37
  • 1
    dc5 has it right. One of the ID's is a string, the other isn't. I'm still confused though because I'm pretty sure it's invalid JavaScript to not have one of those IDs in quotes. – Dan455 Jul 23 '13 at 17:51
  • Agreed - not sure how that isn't causing an error... – dc5 Jul 23 '13 at 17:57
  • Based on the comments in my answer below, looks like mongoose is being used. I would suggest updating your question, examples and tags with all relevant dependencies and logic - likely you will be a faster/better answer that way. Either that or mark this one as answered as the impedence mismatch between the input and the compared values is the culprit and start a new question re: mongoose/objectId-string comparisons. – dc5 Jul 23 '13 at 18:35
  • Thanks will do, want to update your answer to that? – Lion789 Jul 23 '13 at 22:20
  • http://stackoverflow.com/questions/11637353/comparing-mongoose-id-and-strings Thank you this question just answered it, all I had to do is add .equals(otherObject) – Lion789 Jul 23 '13 at 23:29

3 Answers3

4

One problem you have is the location where you are attempting to log the result of isFriend. It's currently being logged just after you set isFriend to false as you enter the search loop.

That statement needs to be moved just after the inner for loop.

Without having all of the inputs, it makes it very difficult to guess where the problem might be.

Using the following as input (Can you provide what the actual input is in JSON format?):

var users = [
    {
        lastName: 'Smith',
        '_id': "51ee2017c2023cc816000001"
    },
    {
        lastName: 'Jones',
        '_id': "51ee2017c2023cc816000002"
    },
    {
        lastName: 'Macks',
        '_id': "51ee2017c2023cc816000003"
    }
];

var signedInUser = {
    friendRequest: [{
        "friendId": "51ee2017c2023cc816000002",
        "read": 0,
        "date_requested": "2013-07-23T06:29:39.021Z"
    }, {
        "friendId": "51ee203cc2023cc816000003",
        "read": 0,
        "date_requested": "2013-07-23T06:42:37.872Z"
    }]
};

function test(err, signedInUser) {
    console.log("\nsignedInUser.friendRequest\n" + JSON.stringify(signedInUser.friendRequest, null, 2));
    for (var x = 0; x < users.length; x++) {
        users[x].isFriend = false;
        console.log("\n" + users[x].lastName);
        for (var i = 0; i < signedInUser.friendRequest.length; i++) {
            console.log(users[x]._id + ' - ' + signedInUser.friendRequest[i].friendId);
            if (users[x]._id === signedInUser.friendRequest[i].friendId) {
                users[x].isFriend = true;
                console.log('test');
                break;
            }
        }
        console.log(users[x].isFriend);
    }

    console.log("\nFinal users:\n" + JSON.stringify(users, null, 2));
}

test(null, signedInUser);

I see the following results:

signedInUser.friendRequest
[
  {
    "friendId": "51ee2017c2023cc816000002",
    "read": 0,
    "date_requested": "2013-07-23T06:29:39.021Z"
  },
  {
    "friendId": "51ee203cc2023cc816000003",
    "read": 0,
    "date_requested": "2013-07-23T06:42:37.872Z"
  }
]

Smith
51ee2017c2023cc816000001 - 51ee2017c2023cc816000002
51ee2017c2023cc816000001 - 51ee203cc2023cc816000003
false

Jones
51ee2017c2023cc816000002 - 51ee2017c2023cc816000002
test
true

Macks
51ee2017c2023cc816000003 - 51ee2017c2023cc816000002
51ee2017c2023cc816000003 - 51ee203cc2023cc816000003
false

Final users:
[
  {
    "lastName": "Smith",
    "_id": "51ee2017c2023cc816000001",
    "isFriend": false
  },
  {
    "lastName": "Jones",
    "_id": "51ee2017c2023cc816000002",
    "isFriend": true
  },
  {
    "lastName": "Macks",
    "_id": "51ee2017c2023cc816000003",
    "isFriend": false
  }
]

Other than the log statement being in the wrong place (I don't think I changed the semantics of your code), with this set of inputs, the logic works. It is likely the input you were expecting is not what you are receiving.

It turns out the OP was using the mongoose native driver for nodejs and, after researching found the answer to the comparison portion of the problem here: Comparing mongoose _id and strings

Community
  • 1
  • 1
dc5
  • 12,341
  • 2
  • 35
  • 47
  • Ok I have included the inputs and the results of calling them through console.log, as you can see both users are in the friendId array so I am not sure as to why it shows as false and does not even enter the loop since console.log('test'); does not get called – Lion789 Jul 23 '13 at 17:46
  • There's your problem. You are comparing `_id: 51ee2017c2023cc816000002` (not a string) to `"friendId":"51ee2017c2023cc816000002"` (a string) – dc5 Jul 23 '13 at 17:49
  • I have this being called on the friendId - {friendId: mongoose.Types.ObjectId(req.body.friendRequest) is that not changing it to an id, so how do I go about fixing it? – Lion789 Jul 23 '13 at 17:52
  • I have done the double equal sign and it still does not output correctly – Lion789 Jul 23 '13 at 17:55
  • Not sure about mongoose - perhaps calling it on the id itself rather than the whole request? [Maybe this question will help...](http://stackoverflow.com/questions/15003010/query-mongoose-schema-by-objectid) – dc5 Jul 23 '13 at 18:25
  • I tried that, by adding ._id at the end of the request... Also, do you know of a way to see what the type of the data is i tried typeof but it returns both as objects and does not tell me an exact type. for example I did this console.log(typeof(users[x].isFriend)); – Lion789 Jul 23 '13 at 18:37
  • 1
    You could try this: `[Object.prototype.toString.call(value)]`(http://stackoverflow.com/questions/472418/why-is-4-not-an-instance-of-number#472427) or debug it using nodes debugging capabilities or something like [node-inspector](https://github.com/node-inspector/node-inspector) – dc5 Jul 23 '13 at 18:48
0

I'd suggest comparing VALUES, not OBJECTS - use ==, not ===, based on this:

Why Array.indexOf doesn't find identical looking objects

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

This is a wild guess, but I suspect you are attempting to return the value here:

res.render('searchResults', {title: 'Weblio', userAdded: users });

If so, user added will have the users collection under userAdded, not a true/false.

You might need to set a boolean value to true (e.g. myVariable = true) when you break of the loop and use that variable as your return value.

Hector Correa
  • 26,290
  • 8
  • 57
  • 73