2

I've got a problem with MongoDB. When I make something like :

User.find({}, (err, result) => { })

I get something like :

[{
_id: someId
name: someName
surname: someSurname
}]

When I copy it to clipboard and paste to any variable like :

let a = [{
"_id": "someId"
"name": "someName"
"surname": "someSurname"
}]

And I check if ( a === result ), I get false and its not the same. My question is why, and how to fix it cause I need change "result" to something like "a"

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130

3 Answers3

0

As per Mukesh Sharma's response, you are not using the equal operator correctly.

When using ===, you test if objects themselves to point to the same reference (which is definitely not the case).

You seem to want to test if two arrays (which are also objects with special properties) are equal. In this case, using a simple equality will never work. You have to iterate through all objects in the array, and then, for each object, iterate through all the keys and check if they are similar to the correspondent of the other array.

You can refer to this answer to check how you can compare two objects. The end result should look like this:

// assuming you use ES6
let array1 = [{ a: 1, b: 2 }];
let array2 = [{ a: 1, b: 2 }];

// check if the arrays have different length     
if (array1.length !== array2.length) { 
    // definitely not equal
    return false;
}}

let n = array1.length;

for (let i = 0; i < n; i++) {
    let res = deepObjCmp(array1[i], array2[i]);
    if (!res) {
        // at least one object is different
        return false;
    }
}
Alex Florin
  • 431
  • 5
  • 14
0

A way to compare two objects is to convert them to JSON and check if the resulting strings are equal

function jsonEqual(a,b) {
    return JSON.stringify(a) === JSON.stringify(b);
} 
jsonEqual(user1, user2) // true in all cases

Sample taken from this link http://www.mattzeunert.com/2016/01/28/javascript-deep-equal.html Just refer it you will understand.

Syed Ayesha Bebe
  • 1,797
  • 1
  • 15
  • 26
0

If you want to compare only _id, name & surname properties, you can manually check each property. This method would probably the most efficient way for your needs.

function isEqual(documentOne, documentTwo) {
  return (documentOne._id.toString() === documentTwo._id.toString() && documentOne.name === documentTwo.name && documentOne.surname === documentTwo.surname);
}

isEqual(a[0], result[0]);
explorer
  • 944
  • 8
  • 18