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
If you only want to get the info without all mongoose benefits, save i.e., you can use .lean() in your query. It will get your info quicker and you'll can use it as an object directly.
https://mongoosejs.com/docs/api.html#query_Query-lean
As says in docs, this is the best to read-only scenarios.
A better way to tackle an issue like this is using doc.toObject()
like this
doc.toObject({ getters: true })
other options include:
getters:
apply all getters (path and virtual getters)virtuals:
apply virtual getters (can override getters option)minimize:
remove empty objects (defaults to true)transform:
a transform function to apply to the resulting document before returningdepopulate:
depopulate any populated paths, replacing them with their original refs (defaults to false)versionKey:
whether to include the version key (defaults to true)so for example you can say
Model.findOne().exec((err, doc) => {
if (!err) {
doc.toObject({ getters: true })
console.log('doc _id:', doc._id) // or title
}
})
and now it will work
Make sure that you have defined title in your schema:
var MyCollectionSchema = new mongoose.Schema({
_id: String,
title: String
});
You don't have whitespace or funny characters in ' title'
, do you? They can be defined if you've quoted identifiers into the object/map definition. For example:
var problem = {
' title': 'Foo',
'content': 'Bar'
};
That might cause console.log(item)
to display similar to what you're expecting, but cause your undefined
problem when you access the title
property without it's preceding space.
I think using 'find' method returns an array of Documents.I tried this and I was able to print the title
for (var i = 0; i < doc.length; i++) {
console.log("iteration " + i);
console.log('ID:' + docs[i]._id);
console.log(docs[i].title);
}
Are you initializing your object?
function MyObject()
{
this.Title = "";
this.Content = "";
}
var myo1 = new MyObject();
If you do not initialize or have not set a title. You will get undefined.