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: '[email protected]',
    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: '[email protected]',
    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: '[email protected]',
  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: '[email protected]',
    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: '[email protected]',
    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: '[email protected]',
  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
17
  • 1
    What is the output, and what output do you expect? Commented Jul 23, 2013 at 16:03
  • 2
    In the current post, your console.log statements are BEFORE the assignment. Commented Jul 23, 2013 at 16:30
  • 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? Commented Jul 23, 2013 at 16:45
  • 1
    That isn't descriptive enough, what is the output of console.log(users)? Commented Jul 23, 2013 at 17:14
  • 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. Commented Jul 23, 2013 at 17:51

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

7 Comments

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
There's your problem. You are comparing _id: 51ee2017c2023cc816000002 (not a string) to "friendId":"51ee2017c2023cc816000002" (a string)
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?
I have done the double equal sign and it still does not output correctly
You could try this: [Object.prototype.toString.call(value)](stackoverflow.com/questions/472418/…) or debug it using nodes debugging capabilities or something like node-inspector
|
0

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

Why Array.indexOf doesn't find identical looking objects

2 Comments

I don't think his ids are objects. And even then using == instead of === would make no difference.
I have tried that, it still gives the incorrect output for some reason
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.

3 Comments

You are correct but, users.isFriend should now be a method that can be called on the value no?
The isFriend value will be on each element of the collection, for example: users[0].isFriend and users[1].isFriend
correct and it should return true or false depending on what 0 or 1 resulted in, in the loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.