如何使用find()方法按自定义日期格式从MongoDB集合检索数据
find() Got it, let's break down how to fetch your customer data from the Customers collection and format the Join_Date field exactly how you want. Here are two reliable approaches:
1. Auto-Format Dates via Schema Transform (Recommended)
You can modify your Mongoose Schema to automatically transform the Join_Date whenever a document is converted to JSON or a plain object. This way, every query will return formatted dates without extra code in your routes.
Update your Schema definition like this:
import mongoose from 'mongoose'; const Customers = mongoose.Schema({ CustomerID: { type: String, default: "" }, Name: { type: String, default: "" }, Email: { type: String, default: "" }, PhoneNumber: { type: String, default: "" }, Join_Date: { type: Date, default: null } }, { collection: 'Customers', // Transform for JSON responses (used when sending data to clients) toJSON: { transform: function(doc, ret) { if (ret.Join_Date) { // Example 1: YYYY-MM-DD format ret.Join_Date = ret.Join_Date.toISOString().split('T')[0]; // Example 2: More flexible format (e.g., "January 15, 2024") // ret.Join_Date = new Intl.DateTimeFormat('en-US', { // year: 'numeric', // month: 'long', // day: 'numeric' // }).format(ret.Join_Date); } return ret; } }, // Transform for plain object conversions (useful if you need to manipulate data server-side) toObject: { transform: function(doc, ret) { if (ret.Join_Date) { ret.Join_Date = ret.Join_Date.toISOString().split('T')[0]; } return ret; } } }); export default mongoose.model('Customers', Customers);
Then implement your route controller with a simple find() query:
import Customers from "./Customers"; router.post('/List_All_Customers', async (req, res) => { try { // Fetch all customers - dates will be auto-formatted thanks to the Schema transform const allCustomers = await Customers.find({}); res.status(200).json({ success: true, data: allCustomers }); } catch (error) { res.status(500).json({ success: false, message: error.message }); } });
2. Manual Date Formatting After Query
If you don't want to modify your Schema, you can format dates manually after fetching the data. This is great for one-off formatting needs.
Here's how to adjust your route controller:
import Customers from "./Customers"; router.post('/List_All_Customers', async (req, res) => { try { const allCustomers = await Customers.find({}); // Map through each customer to format the Join_Date const formattedCustomers = allCustomers.map(customer => { const customerObj = customer.toObject(); // Convert Mongoose document to plain JS object if (customerObj.Join_Date) { // Customize the format here - example: MM/DD/YYYY customerObj.Join_Date = `${customerObj.Join_Date.getMonth() + 1}/${customerObj.Join_Date.getDate()}/${customerObj.Join_Date.getFullYear()}`; // Alternative: Use Intl.DateTimeFormat for locale-aware formatting // customerObj.Join_Date = new Intl.DateTimeFormat('es-ES', { // year: 'numeric', // month: '2-digit', // day: '2-digit' // }).format(customerObj.Join_Date); } return customerObj; }); res.status(200).json({ success: true, data: formattedCustomers }); } catch (error) { res.status(500).json({ success: false, message: error.message }); } });
Bonus: Filter Customers by Date Range
If you need to fetch only customers who joined within a specific date range, add a query condition to find():
// Example: Get customers who joined on or after January 1, 2023 const startDate = new Date('2023-01-01'); const filteredCustomers = await Customers.find({ Join_Date: { $gte: startDate } });
内容的提问来源于stack exchange,提问作者Ratan Uday Kumar

