I have the following code in Node.js.
var getQuestionsByUserId = function (config) {
var query = {
_id: ObjectId(String(config.userId))
};
var projection = {
categoryIds: true,
_id: false
};
var respondWithCategories = function (error, docs) {
var categoryIdsList = []; // empty array
if (docs.length > 0) {
console.log("Inside if: ", docs[0]); // as expected
categoryIdsList = docs[0].categoryIds; // becomes undefined !! the mystery statement
}
console.log("Outside if: ", docs, categoryIdsList); // as expected considering above steps
};
UserModel.find(query, projection, respondWithCategories);
};
The output is as follows
Inside if: { categoryIds: [ 5731892996a8d72df29d8554, 572f9eb779c548660331071b ] }
Outside if: [ { categoryIds: [ 5731892996a8d72df29d8554, 572f9eb779c548660331071b ] } ] undefined
I am using Mongodb with Mongoose for accessing.
Mongodb version: v3.2.1
Node.js version: v5.5.0
The problem is pretty simple. How do I get the categoryIds
from the object.
docs
is an array with single object.
categoryIds
is the only field in the object with a value of an array.
So I accessed by docs[0].categoryIds
. I am getting undefined
!
What am I missing here ?
I tried it on the browser js console and it is working fine !
Edit: (Defending the uniqueness of this question)
This question, marked duplicate, has nothing to do with the asynchronous nature or callbacks even though I have mentioned the callback from mongodb find method.
This question has to do with the mysterious nature (which I feel I am missing something) of the object in the array or the ObjectId interfering with the array or some way to parse the JSON object without altering the ObjectId
fields returned by the mongodb.
So, please remove the duplicate marking for this question and let others help me here.