Danushka herath
Danushka herath

Reputation: 986

Express Node js sort schema objects in route

I created an application with Node js Express and I need know how to sort a schema object in the route controller. My Database is Mongo db. Here is my current working Code.

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import License from './models/license'

const app = express();
const router = express.Router();
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost/tnod');

const connection = mongoose.connection;
connection.once('open', () => {
    console.log('MongoDB database connection established successfully!');
});
app.use('/', router);

router.route('/license').get((req, res) => {
    License.find((err, licenses) => {
        if(err)
            console.log(err);
        else
            res.json(licenses);
    });
});

I need something like License.sort({"votes":1}).find() ... Tried in different ways. Not working!

Somehow I need to sort the schema object given by /license route

Upvotes: 1

Views: 5060

Answers (2)

Ashok
Ashok

Reputation: 2932

Unfortunately, find() doesn't return call back function like you did

License.find((err, licenses) => {})

In Mongoose, a sort can be done in any of the following ways:

License.find({}).sort('votes').exec((err, licenses) => { ... });
License.find({}).sort([['votes', 1]]).exec((err, licenses) => { ... });
License.find({}).sort({votes: 1}).exec((err, licenses) => { ... });
License.find({}, null, {sort: {votes: 1}}, (err, licenses) => { ... });

There’s a special syntax to work with promises in a more comfortable fashion, called “async/await”.

const licenses = await License.find({}).sort({'votes': 1})

For run that you need to make function async In your code case

router.route('/license').get(async(req, res) => {
    try{
        const licenses = await License.find({}).sort({'votes': 1})
        res.json(licenses);
    } catch(e) {
      console.log('error:-', e)
    }
}}

Most Important License.find({ //pass condition to filter your data })

Upvotes: 1

Anand S
Anand S

Reputation: 820

Following examples return all documents in the collection named License sorted by the votes field in ascending order. Specify a value to orderby of negative one to sort in descending order or a positive value (e.g. 1) to sort in ascending order.

 License
  .find()
  .orderby({"votes":1})
  then(response => {
   console.log(response);
   })
   .catch(error => {
   console.log(error);
    });

Upvotes: 0

Related Questions