H
H
hollanditkzn2017-11-10 11:50:41
Node.js
hollanditkzn, 2017-11-10 11:50:41

How to display all records from mongoose?

I'm reading the documentation and I don't understand how to display all entries on the screen. I'm reading mongoosejs.com/docs/queries.html and I don't quite understand how to output
In the router I specify

let express = require('express'),
  Order = require('../models/order'),
  router = express.Router();

/* GET users listing. */
router.get('/', (req, res) => {
  console.log(Order.find());
  res.render('user', {
    username: req.user.username,
    title: 'Главная страница',
    order: Order.find()
  });
});

And in the model
let mongoose = require('../bin/mongoose'),
  passportLocalMongoose = require('passport-local-mongoose'),
  Schema = mongoose.Schema;

let schema = new Schema({
  username: {
    type: String,
  },
  password: {
    type: String,
  },
  created: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('User', schema);

But I don't understand how to get them out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Coder321, 2017-11-10
@Coder321

router.get('/', (req, res) => {
  Order.find()
    .then(orders => {
      res.render('user', {
        username: req.user.username,
        title: 'Главная страница',
        order: orders
      });
    })
    .catch(error => {
      console.log(error);
    })
  /* Вариант с калбеком
Order.find((error, orders) => {
  if (error) {
    console.log(error);
  }
  res.render('user', {
    username: req.user.username,
    title: 'Главная страница',
    order: orders
  });
})*/
});

or if you are using 8.x node
router.get('/', async (req, res) => {

  try {
    const orders = await Order.find();
    res.render('user', {
      username: req.user.username,
      title: 'Главная страница',
      order: orders
    });
  } catch (error) {
    console.log(error);
  }

});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question