I have this script to try to convert the current date as string
Date: 'Thu Oct 19 2023 11:49:00 GMT+0200 (Central European Summer Time)',
Into a Date format that mongoose can understand and sort
import config from 'config';
const url = config.get('mongoURI');
const dbname = config.get('dbname');
const db = `${url}${dbname}`;
mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const Tweet = mongoose.model('Tweet', {
Date: Date, // Make sure your schema uses the Date data type for the Date field
User: String,
Tweet: String,
URL: String
});
async function updateDates() {
try {
const tweetsToUpdate = await Tweet.find({});
for (const tweet of tweetsToUpdate) {
try {
const currentDate = tweet.Date;
const date = new Date(currentDate);
if (!isNaN(date)) {
tweet.Date = date;
await tweet.save();
console.log(`Updated Date for tweet ${tweet._id}`);
} else {
console.warn(`Skipped invalid date for tweet ${tweet._id}: ${currentDate}`);
}
} catch (error) {
console.error(`Error updating tweet ${tweet._id}:`, error);
}
}
console.log('Data migration completed.');
} catch (error) {
console.error('Data migration failed:', error);
} finally {
mongoose.disconnect();
}
}
// Run the data migration script
updateDates();
It says all is good, but when I use this line on mongosh
db.tweets.aggregate([ { $limit: 1 }, { $project: { DateType: { $type: "$Date" } } } ])
I get:
[ { _id: ObjectId("6532e51c9dffaadae4a774ab"), DateType: 'string' } ]
So mongoose is unable to order the date using
await Tweets.find(query).sort({ Date: 1})