• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

[Object object] mongoose zwaraca takie wartości

Object Storage Arubacloud
0 głosów
127 wizyt
pytanie zadane 15 sierpnia 2020 w JavaScript przez Darth_Sith Początkujący (310 p.)
edycja 15 sierpnia 2020 przez Darth_Sith

 

const express = require('express');
const router = express.Router();
const Task = require('../models/Tasks')

//  @desc GET /dashboard
router.get('/', (req, res) => {
  res.render('dashboard')
})

//  @desc GET /dashboard/task
router.get('/task', (req, res) => {
  res.render('task')
})

//  @desc GET /dashboard/fulllist
// router.get('/task/fulllist', async (req, res) => {
//   try {

//     let tablee = Task.find({
//       author: req.body.author
//     });

//     res.render('fulllist', {
//       author: req.body.author,
//       table: tablee
//     })

//   } catch (e) {
//     console.log(e)
//   }
// })

//  @desc POST /dashboard/task
router.post('/task/fulllist', async (req, res) => {
  try {
    let task = new Task({
      title: req.body.title,
      author: req.body.author,
      body: req.body.body,
      createdAt: Date.now()
    })

    await task.save(task)

    let table = Task.find({
      author: req.body.author
    });

    res.render('fulllist', {
      author: req.body.author,
      table
    })

  } catch (e) {
    console.log(e)
  }
})

module.exports = router;
{% extends 'layout.twig' %}

{% block body %}
  
  <h1>Witaj, {{ author }}</h1>
  
  {# <p>{{title}}</p>
  <p>{{author}}</p>
  <p>{{body}}</p>
  <p>{{createdAt}}</p>   #}
  <table>

    {% for item in table %}
      <td>{{item}}</td>
    {% endfor %}

  </table>

{% endblock %}

Witam, mam problem a mianowicie nie wiem czemu zawraca mi [Object object] zamiast całą kolekcje. Ktoś coś wie na ten temat ? Dodatkowo na podstronie /task/fulllist przy odświeżaniu przesyła mi dodatkowy rekord do bazy danych. + jak console.log(table) zwraca mi undefined :/

komentarz 15 sierpnia 2020 przez ScriptyChris Mędrzec (190,190 p.)

Wykonsoluj zmienną table (zwrotka z Task.find) i pokaż co tam jest.

komentarz 16 sierpnia 2020 przez Darth_Sith Początkujący (310 p.)
Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map {}, _posts: Map {} },
  _executionCount: 0,
  mongooseCollection: NativeCollection {
    collection: Collection { s: [Object] },
    Promise: [Function: Promise],
    _closed: false,
    opts: {
      schemaUserProvidedOptions: {},
      capped: false,
      autoCreate: undefined,
      Promise: [Function: Promise],
      '$wasForceClosed': undefined
    },
    name: 'tasks',
    collectionName: 'tasks',
    conn: NativeConnection {
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: [Object],
      replica: false,
      options: null,
      otherDbs: [],
      relatedDbs: {},
      states: [Object: null prototype],
      _readyState: 1,
      _closeCalled: false,
      _hasOpened: true,
      plugins: [],
      id: 0,
      _listening: false,
      _connectionOptions: [Object],
      client: [MongoClient],
      '$initialConnection': [Promise],
      _events: [Object: null prototype],
      _eventsCount: 1,
      name: 'create-app',
      host: 'cluster0-shard-00-00-t0cfg.mongodb.net',
      port: 27017,
      user: 'dered00',
      pass: 'karmas123',
      db: [Db]
    },
    queue: [],
    buffer: false,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined
    }
  },
  model: Model { Tasks },
  schema: Schema {
    obj: {
      title: [Object],
      author: [Object],
      body: [Object],
      createdAt: [Object]
    },
    paths: {
      title: [SchemaString],
      author: [SchemaString],
      body: [SchemaString],
      createdAt: [SchemaDate],
      _id: [ObjectId],
      __v: [SchemaNumber]
    },
    aliases: {},
    subpaths: {},
    virtuals: { id: [VirtualType] },
    singleNestedPaths: {},
    nested: {},
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: {},
    methodOptions: {},
    statics: {},
    tree: {
      title: [Object],
      author: [Object],
      body: [Object],
      createdAt: [Object],
      _id: [Object],
      __v: [Function: Number],
      id: [VirtualType]
    },
    query: {},
    childSchemas: [],
    plugins: [ [Object], [Object], [Object], [Object], [Object] ],
    '$id': 1,
    s: { hooks: [Kareem] },
    _userProvidedOptions: {},
    options: {
      typePojoToMixed: true,
      typeKey: 'type',
      id: true,
      noVirtualId: false,
      _id: true,
      noId: false,
      validateBeforeSave: true,
      read: null,
      shardKey: null,
      autoIndex: null,
      minimize: true,
      discriminatorKey: '__t',
      versionKey: '__v',
      capped: false,
      bufferCommands: true,
      strict: true,
      pluralization: true
    },
    '$globalPluginsApplied': true,
    _requiredpaths: [ 'body', 'author', 'title' ]
  },
  op: 'find',
  options: {},
  _conditions: { author: 'Paolo ' },
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: NodeCollection {
    collection: NativeCollection {
      collection: [Collection],
      Promise: [Function: Promise],
      _closed: false,
      opts: [Object],
      name: 'tasks',
      collectionName: 'tasks',
      conn: [NativeConnection],
      queue: [],
      buffer: false,
      emitter: [EventEmitter]
    },
    collectionName: 'tasks'
  },
  _traceFunction: undefined,
  '$useProjection': true
}
Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map {}, _posts: Map {} },
  _executionCount: 0,
  mongooseCollection: NativeCollection {
    collection: Collection { s: [Object] },
    Promise: [Function: Promise],
    _closed: false,
    opts: {
      schemaUserProvidedOptions: {},
      capped: false,
      autoCreate: undefined,
      Promise: [Function: Promise],
      '$wasForceClosed': undefined
    },
    name: 'tasks',
    collectionName: 'tasks',
    conn: NativeConnection {
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: [Object],
      replica: false,
      options: null,
      otherDbs: [],
      relatedDbs: {},
      states: [Object: null prototype],
      _readyState: 1,
      _closeCalled: false,
      _hasOpened: true,
      plugins: [],
      id: 0,
      _listening: false,
      _connectionOptions: [Object],
      client: [MongoClient],
      '$initialConnection': [Promise],
      _events: [Object: null prototype],
      _eventsCount: 1,
      name: 'create-app',
      host: 'cluster0-shard-00-00-t0cfg.mongodb.net',
      port: 27017,
      user: 'dered00',
      pass: 'karmas123',
      db: [Db]
    },
    queue: [],
    buffer: false,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined
    }
  },
  model: Model { Tasks },
  schema: Schema {
    obj: {
      title: [Object],
      author: [Object],
      body: [Object],
      createdAt: [Object]
    },
    paths: {
      title: [SchemaString],
      author: [SchemaString],
      body: [SchemaString],
      createdAt: [SchemaDate],
      _id: [ObjectId],
      __v: [SchemaNumber]
    },
    aliases: {},
    subpaths: {},
    virtuals: { id: [VirtualType] },
    singleNestedPaths: {},
    nested: {},
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: {},
    methodOptions: {},
    statics: {},
    tree: {
      title: [Object],
      author: [Object],
      body: [Object],
      createdAt: [Object],
      _id: [Object],
      __v: [Function: Number],
      id: [VirtualType]
    },
    query: {},
    childSchemas: [],
    plugins: [ [Object], [Object], [Object], [Object], [Object] ],
    '$id': 1,
    s: { hooks: [Kareem] },
    _userProvidedOptions: {},
    options: {
      typePojoToMixed: true,
      typeKey: 'type',
      id: true,
      noVirtualId: false,
      _id: true,
      noId: false,
      validateBeforeSave: true,
      read: null,
      shardKey: null,
      autoIndex: null,
      minimize: true,
      discriminatorKey: '__t',
      versionKey: '__v',
      capped: false,
      bufferCommands: true,
      strict: true,
      pluralization: true
    },
    '$globalPluginsApplied': true,
    _requiredpaths: [ 'body', 'author', 'title' ]
  },
  op: 'find',
  options: {},
  _conditions: { author: 'Paolo ' },
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: NodeCollection {
    collection: NativeCollection {
      collection: [Collection],
      Promise: [Function: Promise],
      _closed: false,
      opts: [Object],
      name: 'tasks',
      collectionName: 'tasks',
      conn: [NativeConnection],
      queue: [],
      buffer: false,
      emitter: [EventEmitter]
    },
    collectionName: 'tasks'
  },
  _traceFunction: undefined,
  '$useProjection': true
}

 

1
komentarz 16 sierpnia 2020 przez ScriptyChris Mędrzec (190,190 p.)

Jeśli wywołasz Task.find przekazując jako drugi parametr callback, to czy argument result jest tym samym co konsola pokazała w poprzednim komentarzu, czy już zawiera konkretnie poszukiwaną kolekcję?

Task.find({
  author: req.body.author
}, function(err, result) {
  if (err) {
    console.error('err', err);

    return err;
  }

  console.log('result: ', result);
});

https://mongoosejs.com/docs/api.html#model_Model.find

komentarz 19 sierpnia 2020 przez Darth_Sith Początkujący (310 p.)
edycja 19 sierpnia 2020 przez Darth_Sith

 

Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map {}, _posts: Map {} },
  _executionCount: 0,
  mongooseCollection: NativeCollection {
    collection: Collection { s: [Object] },        
    Promise: [Function: Promise],
    _closed: false,
    opts: {
      schemaUserProvidedOptions: {},
      capped: false,
      autoCreate: undefined,
      Promise: [Function: Promise],
      '$wasForceClosed': undefined
    },
    name: 'tasks',
    collectionName: 'tasks',
    conn: NativeConnection {
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: [Object],
      replica: false,
      options: null,
      otherDbs: [],
      relatedDbs: {},
      states: [Object: null prototype],
      _readyState: 1,
      _closeCalled: false,
      _hasOpened: true,
      plugins: [],
      id: 0,
      _listening: false,
      _connectionOptions: [Object],
      client: [MongoClient],
      '$initialConnection': [Promise],
      _events: [Object: null prototype],
      _eventsCount: 1,
      name: 'create-app',
      host: 'cluster0-shard-00-00-t0cfg.mongodb.net',
      port: 27017,
      user: 'dered00',
      pass: 'karmas123',
      db: [Db]
    },
    queue: [],
    buffer: false,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined
    }
  },
  model: Model { Tasks },
  schema: Schema {
    obj: {
      title: [Object],
      author: [Object],
      body: [Object],
      createdAt: [Object]
    },
    paths: {
      title: [SchemaString],
      author: [SchemaString],
      body: [SchemaString],
      createdAt: [SchemaDate],
      _id: [ObjectId],
      __v: [SchemaNumber]
    },
    aliases: {},
    subpaths: {},
    virtuals: { id: [VirtualType] },
    singleNestedPaths: {},
    nested: {},
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: {},
    methodOptions: {},
    statics: {},
    tree: {
      title: [Object],
      author: [Object],
      body: [Object],
      createdAt: [Object],
      _id: [Object],
      __v: [Function: Number],
      id: [VirtualType]
    },
    query: {},
    childSchemas: [],
    plugins: [ [Object], [Object], [Object], [Object], [Object] ],
    '$id': 1,
    s: { hooks: [Kareem] },
    _userProvidedOptions: {},
    options: {
      typePojoToMixed: true,
      typeKey: 'type',
      id: true,
      noVirtualId: false,
      _id: true,
      noId: false,
      validateBeforeSave: true,
      read: null,
      shardKey: null,
      autoIndex: null,
      minimize: true,
      discriminatorKey: '__t',
      versionKey: '__v',
      capped: false,
      bufferCommands: true,
      strict: true,
      pluralization: true
    },
    '$globalPluginsApplied': true,
    _requiredpaths: [ 'body', 'author', 'title' ]
  },
  op: 'find',
  options: {},
  _conditions: { author: 'Paolo ' },
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: NodeCollection {
    collection: NativeCollection {
      collection: [Collection],
      Promise: [Function: Promise],
      _closed: false,
      opts: [Object],
      name: 'tasks',
      collectionName: 'tasks',
      conn: [NativeConnection],
      queue: [],
      buffer: false,
      emitter: [EventEmitter]
    },
    collectionName: 'tasks'
  },
  _traceFunction: undefined,
  '$useProjection': true
}
POST /dashboard/task/fulllist 200 372.093 ms - 852
result:  [
  {
    _id: 5f38c95d08588b477c5a6c89,
    title: 'Erragon',
    author: 'Paolo ',
    body: 'This is Eragon story',
    createdAt: 2020-08-16T05:51:25.480Z,
    __v: 0
  },
  {
    _id: 5f38c979f34f401264bcaa30,
    title: 'Erragon',
    author: 'Paolo ',
    body: 'This is Eragon story',
    createdAt: 2020-08-16T05:51:53.713Z,
    __v: 0
  },
  {
    _id: 5f3ca3d43210492140098387,
    title: 'Erragon',
    author: 'Paolo ',
    body: 'This is Eragon story',
    createdAt: 2020-08-19T04:00:20.094Z,
    __v: 0
  },
  {
    _id: 5f3ca40772a75d29d84e85c0,
    title: 'Erragon',
    author: 'Paolo ',
    body: 'This is Eragon story',
    createdAt: 2020-08-19T04:01:11.021Z,
    __v: 0
  },
  {
    _id: 5f3ca49139dd3a25e80b7690,
    title: 'Erragon',
    author: 'Paolo ',
    body: 'This is Eragon story',
    createdAt: 2020-08-19T04:03:29.978Z,
    __v: 0
  }
]

Nie wiem w jaki sposób renderować pojedyńcze wartości do tabeli. Możecie zapodać jakiś przykład ?

1
komentarz 19 sierpnia 2020 przez ScriptyChris Mędrzec (190,190 p.)

Od 145 linijki tego, co pokazała konsola masz kolekcję z Mongoose dostępną w argumencie result w callbacku. Są to kolejne obiekty:

{
    _id: 5f38c95d08588b477c5a6c89,
    title: 'Erragon',
    author: 'Paolo ',
    body: 'This is Eragon story',
    createdAt: 2020-08-16T05:51:25.480Z,
    __v: 0
  },

Wcześniejsza część loga wygląda jak ta ze zmiennej table, do której przypisałeś wynik wywołania metody Task.find.

Zmienną result możesz renderować w tabeli. Tzn. raczej nie wyrenderujesz w DOM obiektów tej kolekcji, raczej powinieneś wyświetlać ich kolejne propertisy (wybrane lub wszystkie), ewentualnie wyrenderuj obiekty jako JSON.

Zaloguj lub zarejestruj się, aby odpowiedzieć na to pytanie.

Podobne pytania

+1 głos
0 odpowiedzi 82 wizyt
pytanie zadane 20 września 2020 w JavaScript przez poldeeek Mądrala (5,980 p.)
0 głosów
0 odpowiedzi 197 wizyt
pytanie zadane 29 października 2018 w JavaScript przez Alex.Ironside Stary wyjadacz (14,900 p.)
0 głosów
1 odpowiedź 200 wizyt
pytanie zadane 22 stycznia 2018 w JavaScript przez Anoonymous Obywatel (1,560 p.)

92,575 zapytań

141,424 odpowiedzi

319,649 komentarzy

61,960 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj.

Akademia Sekuraka

Kolejna edycja największej imprezy hakerskiej w Polsce, czyli Mega Sekurak Hacking Party odbędzie się już 20 maja 2024r. Z tej okazji mamy dla Was kod: pasjamshp - jeżeli wpiszecie go w koszyku, to wówczas otrzymacie 40% zniżki na bilet w wersji standard!

Więcej informacji na temat imprezy znajdziecie tutaj. Dziękujemy ekipie Sekuraka za taką fajną zniżkę dla wszystkich Pasjonatów!

Akademia Sekuraka

Niedawno wystartował dodruk tej świetnej, rozchwytywanej książki (około 940 stron). Mamy dla Was kod: pasja (wpiszcie go w koszyku), dzięki któremu otrzymujemy 10% zniżki - dziękujemy zaprzyjaźnionej ekipie Sekuraka za taki bonus dla Pasjonatów! Książka to pierwszy tom z serii o ITsec, który łagodnie wprowadzi w świat bezpieczeństwa IT każdą osobę - warto, polecamy!

...