How to manipulate data returned from mongo db using mongoose

I created a local database using mongo (actually using a tutorial )

It has a db named 'simple' and a 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": " carolegoodman@intrawear.com " } 

Then I create the Person schema and model in my node application

 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); }); }); 

When calling find () in the Person model, I register (for console.log (doc [0])) - the first element in the document is returned:

 { _id: 548e41afa0bad91d53f34cce, id: 0, guid: 'af6a931d-1801-4662-9d52-c95dc97bac22', isActive: false, firstName: 'Janna', lastName: 'Shelton', email: ' crossoconnor@geekology.com ' } 

But my problem is that when I look for the firstName property on doc [0] (ie doc [0] .firstName), I get undefined.

I tried to diagnose this, and Object.keys (doc [0]) gives me:

 [ '$__', 'isNew', 'errors', '_maxListeners', '_doc', '_pres', '_posts', 'save', '_events' ] 

that I suspect that to get the manga you need to use some special methods if you want to access the data from the returned elements, but I can not find the answer in the documentation or here.

thanks

+5
source share
3 answers

You get an array of documents. Mongoose API

 doc[0].get('firstName') 
+2
source

If you just need a simple JavaScript presentation of documents that you can freely manipulate, add lean() to the 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); }); }); 
+1
source

Use .lean () in your query as shown below.

 db.collection.find().lean().then(function(data){}) 
0
source

Source: https://habr.com/ru/post/1209041/


All Articles