Mongodb使用nodejs和mongoose查询嵌套对象

时间:2018-05-31 21:47:12

标签: jquery node.js mongodb mongoose

我有以下架构:

=SUM(SUMIFS('ml5'!G:G,'ml5'!$C:$C,0), 
     SUMIFS('ml6'!G:G,'ml6'!$C:$C,0),
     SUMIFS('ml7'!G:G,'ml5'!$C:$C,0)) /
 SUM(COUNTIFS('ml5'!$C:$C,0),
     COUNTIFS('ml6'!$C:$C,0),
     COUNTIFS('ml5'!$C:$C,0))

我想检索address_place中的数据并查看。 我为地址尝试了以下代码:

var mongoose = require('mongoose');

var Schema = mongoose.Schema;


var Reviews = new Schema(
    {
    author: {type: String},
    rate: {type: Number},
    descritpion: String,
    date: {type: Date, default:Date.now}
    }
);
var Place= new Schema(
    {
        image_path: {type:String},
        place_name: { type: String},
        info: {type: String},
        type: {type: String},
        address_place:[{
            address:{type: String},
            city:{type: String},
            postcode: {type: String}
            }],
        review: [Reviews]
    }
);

var PlaceModel = mongoose.model('Place', Place);
module.exports = PlaceModel;

此代码的结果是终端中的以下内容:

       var PlaceModel = require('../models/places');
       exports.place_list = function(req, res) {
       PlaceModel.find({},
       'place_name info type
        address_place.address address_place.city address_place.postcode',
       function (err, pla) {

        console.log(pla);
        if(err){
            console.log(err);
        }else{
            res.render('place.ejs',{
                title: 'Places',
                placesArray : pla,

            });
        }
    })
}

正如您所看到的,address_places仅在括号中显示" object"但我想检索整个内容。我怎样才能做到这一点?

例如

{ _id: 5b10235c29dd6a29e8a8f5d7,
name: 'Test',
info: 'Test',
address_place: [ [Object] ], 
type: 'Restaurant',
review: [ [ Object ] ],
__v: 0 },

审查同样的事情。我尝试了一切。先感谢您!

1 个答案:

答案 0 :(得分:0)

亲爱的朋友,这只是一个想法:

如何使用它:JSON.stringify(result,undefiend,2);

like this link

然后这将是你的输出:

{
  "results": [
    {
      "gender": "male",
      "name": {
        "title": "mr",
        "first": "andreas",
        "last": "schütz"
      },
      "location": {
        "street": "4662 ahornweg",
        "city": "dessau-roßlau",
        "state": "bremen",
        "postcode": 82616
      },
      "email": "andreas.schütz@example.com",
      "login": {
        "username": "smallfrog599",
        "password": "jesse",
        "salt": "ZSR5HnrB",
        "md5": "9cd89a6e4c13fcd6a70994b4e827a48f",
        "sha1": "17df07fa228bfdbe83f27da5d0668535ce204ef8",
        "sha256": "6de42667cf0a279acb98bd626bd9bfed37fdd9ed0b240d04795b1f734958df4b"
      },
      "dob": "1961-02-25 08:55:55",
      "registered": "2011-04-03 18:22:05",
      "phone": "0078-3005886",
      "cell": "0179-4833906",
      "id": {
        "name": "",
        "value": null
      },
      "picture": {
        "large": "https://randomuser.me/api/portraits/men/69.jpg",
        "medium": "https://randomuser.me/api/portraits/med/men/69.jpg",
        "thumbnail": "https://randomuser.me/api/portraits/thumb/men/69.jpg"
      },
      "nat": "DE"
    }
  ],
  "info": {
    "seed": "2b9dc874234382a8",
    "results": 1,
    "page": 1,
    "version": "1.1"
  }
}

但在此方法之前:

{ status: 200,
  statusText: 'OK',
  headers:
   { date: 'Fri, 01 Jun 2018 01:13:10 GMT',
     'content-type': 'application/json; charset=utf-8',
     'content-length': '900',
     connection: 'close',
     'set-cookie': [ '__cfduid=d8d15d4f5c4a4e98379a01b89e75168191527815590; expires=Sat, 01-Jun-19 01:13:10 GMT; path=/; domain=.randomuser.me; HttpOnly' ],
     'x-powered-by': 'Express',
     'access-control-allow-origin': '*',
     'cache-control': 'no-cache',
     etag: 'W/"384-IffrBotAu5UaTWaDFu0ggg"',
     vary: 'Accept-Encoding',
     'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
     server: 'cloudflare',
     'cf-ray': '423dd0f18be19ab8-FRA' },
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/0.18.0' },
     method: 'get',
     url: 'https://randomuser.me/api/',
     data: undefined },
  request:
   ClientRequest {
     domain: null,
     _events:
      { socket: [Function],
        abort: [Function],
        aborted: [Function],
        error: [Function],
        timeout: [Function],
        prefinish: [Function: requestOnPrefinish] },
     _eventsCount: 6,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: false,
     _last: true,
     upgrading: false,
     chunkedEncoding: false,
     shouldKeepAlive: false,
     useChunkedEncodingByDefault: false,
     sendDate: false,
     _removedConnection: false,
     _removedContLen: false,
     _removedTE: false,
     _contentLength: 0,
     _hasBody: true,
     _trailer: '',
     finished: true,
     _headerSent: true,
     socket:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 9,
        connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'randomuser.me',
        _readableState: [Object],
        readable: false,
        domain: null,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        _bytesDispatched: 131,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: null,
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        read: [Function],
        _consuming: true,
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        [Symbol(asyncId)]: 5,
        [Symbol(bytesRead)]: 1478 },
     connection:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 9,
        connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'randomuser.me',
        _readableState: [Object],
        readable: false,
        domain: null,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: false,
        allowHalfOpen: false,
        _bytesDispatched: 131,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: null,
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        read: [Function],
        _consuming: true,
        _idleNext: null,
        _idlePrev: null,
        _idleTimeout: -1,
        [Symbol(asyncId)]: 5,
        [Symbol(bytesRead)]: 1478 },
     _header: 'GET /api/ HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.18.0\r\nHost: randomuser.me\r\nConnection: close\r\n\r\n',
     _onPendingData: [Function: noopPendingOutput],
     agent:
      Agent {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        defaultPort: 443,
        protocol: 'https:',
        options: [Object],
        requests: {},
        sockets: [Object],
        freeSockets: {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256,
        maxCachedSessions: 100,
        _sessionCache: [Object] },
     socketPath: undefined,
     timeout: undefined,
     method: 'GET',
     path: '/api/',
     _ended: true,
     res:
      IncomingMessage {
        _readableState: [Object],
        readable: false,
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        socket: [Object],
        connection: [Object],
        httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers: [Object],
        rawHeaders: [Array],
        trailers: {},
        rawTrailers: [],
        upgrade: false,
        url: '',
        method: null,
        statusCode: 200,
        statusMessage: 'OK',
        client: [Object],
        _consuming: true,
        _dumped: false,
        req: [Circular],
        responseUrl: 'https://randomuser.me/api/',
        redirects: [],
        read: [Function] },
     aborted: undefined,
     timeoutCb: null,
     upgradeOrConnect: false,
     parser: null,
     maxHeadersCount: null,
     _redirectable:
      Writable {
        _writableState: [Object],
        writable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _options: [Object],
        _redirectCount: 0,
        _redirects: [],
        _requestBodyLength: 0,
        _requestBodyBuffers: [],
        _onNativeResponse: [Function],
        _currentRequest: [Circular],
        _currentUrl: 'https://randomuser.me/api/' },
     [Symbol(outHeadersKey)]: { accept: [Array], 'user-agent': [Array], host: [Array] } },
  data:
   { results: [ [Object] ],
     info: { seed: '9df745e3ce0b0ebc', results: 1, page: 1, version: '1.1' } } }