I've created a local database using mongo (using this tutorial actually)
It has a db named 'simple' and collection named 'people'. Then I import json with each element as
{
"id": 1,
"guid": "1581cfde-f2fc-44f8-8953-511331e943ab",
"isActive": true,
"firstName": "Ilene",
"lastName": "Kent",
"email": "[email protected]"
}
I then create the schema and Person model in my node app
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
app.set('port', (process.env.PORT || 5000));
mongoose.connect('mongodb://localhost/simple')
var personSchema = {
firstname: String,
lastname: String,
email: String
}
var Person = mongoose.model('Person', personSchema, 'people')
app.get('/users', function(req,res){
Person.find(function(err, doc){
var x = doc[0]
console.log(x)
console.log(Object.keys(x))
res.send(200);
});
});
On calling find() on the Person model I get logged (for console.log(doc[0])) - the first item in the doc returned:
{ _id: 548e41afa0bad91d53f34cce,
id: 0,
guid: 'af6a931d-1801-4662-9d52-c95dc97bac22',
isActive: false,
firstName: 'Janna',
lastName: 'Shelton',
email: '[email protected]' }
But my problem is that when I look for the property firstName on doc[0] (i.e. doc[0].firstName) I get an undefined.
I've tried diagnosing this and Object.keys(doc[0]) gives me:
[ '$__',
'isNew',
'errors',
'_maxListeners',
'_doc',
'_pres',
'_posts',
'save',
'_events' ]
meaning I suspect there must be some special methods for mongoose when you want to access the data from your returned elements - but I can't find the answer in documentation or here.
Thanks
You receive an array of Documents. Mongoose API
doc[0].get('firstName')
When you just want a plain JavaScript representation of the documents that you can freely manipulate, add lean()
to your Mongoose query chain:
app.get('/users', function(req,res){
Person.find().lean().exec(function(err, docs){
var x = docs[0]
console.log(x)
console.log(Object.keys(x))
res.send(200);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With