tippenein tippenein - 6 months ago 34
Javascript Question

Mongoose/MongoDB result fields appear undefined in Javascript

Is there something that I'm missing that would allow item to log as an object with a parameter, but when I try to access that parameter, it's undefined?

What I've tried so far:

  • console.log(item)
    { title: "foo", content: "bar" }
    , that's fine

  • console.log(typeof item)
    => object

  • console.log(item.title)
    => "undefined"

I'll include some of the context just in case it's relevant to the problem.

var TextController = function(myCollection) {
this.myCollection = myCollection

TextController.prototype.list = function(req, res, next) {
this.myCollection.find({}).exec(function(err, doc) {
var set = new Set([])
doc.forEach(function(item) {
console.log(item) // Here item shows the parameter
console.log(item.title) // "undefined"

Based on suggestion I dropped
before this line to check what item actually is via the node repl debugger. This is what I found : http://hastebin.com/qatireweni.sm

From this I tried
and it works just fine.. So, this seems more like a mongoose question now than anything.

There are questions similar to this, but they seem to be related to 'this' accessing of objects or they're trying to get the object outside the scope of the function. In this case, I don't think I'm doing either of those, but inform me if I'm wrong. Thanks


Try performing a for in loop over item and see if you can access values.

for (var k in item) {

If it works, it would mean your keys have some non-printable characters or something like this.

From what you said in the comments, it looks like somehow item is an instance of a String primitive wrapper.


var s = new String('test');
typeof s; //object
s instanceof String; //true

To verify this theory, try this:

eval('(' + item + ')').title;

It could also be that item is an object that has a toString method that displays what you see.

EDIT: To identify these issues quickly, you can use console.dir instead of console.log, since it display an interactive list of the object properties. You can also but a breakpoint and add a watch.