首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Mongodb查询嵌套对象的nodejs和mongoose

Mongodb查询嵌套对象的nodejs和mongoose
EN

Stack Overflow用户
提问于 2018-06-01 05:47:12
回答 1查看 1K关注 0票数 0

我有以下架构:

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;

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

       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,

            });
        }
    })
}

此代码在终端中的结果如下所示:

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

正如您所看到的,address_places只显示在方括号"object“中,但我希望检索整个内容。我该怎么做呢?

例如

 address_place: [ 
   address: 'street',
   city: 'New York',
   postcode: 'S23WLL'
  ]

复习也是一样的。我什么都试过了。提前谢谢你!

EN

回答 1

Stack Overflow用户

发布于 2018-06-01 09:26:28

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

使用这个怎么样: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' } } }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50633259

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档