I have defined a User schema as follows:
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
name: {
type: String
},
subscriptions: [{
userID: {
type: String,
required: true,
},
subscriptionDate: {
type: Date,
required: true,
default: Date.now
}
}]
})
In addition, I have a routes.js file with the following content:
const express = require('express')
const router = express.Router()
const User = require('User')
router.get('/', async (req, res) => {
try {
const users = await User.find()
res.json(users)
} catch (err) {
res.status(500).json({message: err.message})
}
})
When making a GET request, I am facing an issue where I need the 'subscriptions' field to be sorted by 'subscriptionDate', displaying only the 5 most recent subscriptions while showing all other information normally. As a beginner in express, mongoDB, and mongoose, I hope my explanation is clear.
How can I achieve the desired output?
For reference, here is my server.js file:
require('dotenv').config();
const express = require('express');
const app = express();
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/subscribers');
const db = mongoose.connection;
db.on('error', (error) => console.error(error));
db.once('open', () => console.log('Connected to Database'));
app.use(express.json());
const router = require("./routes");
app.use('/routes', router);
app.listen(3000, () => console.log('Server Started.'))
I have attempted using collections.find().sort()
, which sorted all users based on subscriptions. I also tried using aggregate([$unwind])
, resulting in splitting users into multiple documents based on their subscriptions.