I'm currently trying to learn NodeJS with MongoDB. I'm using mongoose to connect to a local installed version of MongoDB and am using mocha for my TTD.
I know the solution for this case, but not the reason why it is this way.
Let me explain:
I create a schema and a model called MarioCharacter
.
I save this MarioCharacter
to MongoDB using the .save
function of mongoose.
I want to find this MarioCharacter (there's only one, its variable is "newCharacter
") in the database using it's id.
My code with mongoose and mocha looks like this:
//Find a record by its ID
it("Finds a record by id from the database", function(done) {
MarioCharacter.findOne({_id: newCharacter._id}).then(function(result) {
//Log the value
console.log(newCharacter._id); // returns 5b277477fd8f6f2c6437e5bc
console.log(result._id); // returns 5b277477fd8f6f2c6437e5bc
//Log the type
console.log(typeof newCharacter._id); // returns object
console.log(typeof result._id); // returns object
//Test fails - returns false
assert(result._id === newCharacter._id);
done();
})
});
The solution is to convert both to a string using the .toString()
method, which means that both types don't seem to be the same, even tough it says object on both of them.
What is it that I don't get here? Are there also subtypes of objects or what?