Soy nuevo en MongoDB. Necesito obtener el recuento de las publicaciones que se publican en este mes actual. PlateModel es mi modelo. También he mantenido las marcas de tiempo verdaderas. Se parece a lo siguiente:
{ timestamps: true }
Mi código actual en el controlador se ve a continuación:
const today = new Date(); const host_count = await PlateModel.find({ $and: [ { postedBy: req.user._id, }, { createdAt: today.getMonth(), }, ], }).count();
Pero obtengo el valor de conteo 0. ¿Alguien puede ayudarme a resolver el problema?
Puede filtrar los objetos desde el comienzo del mes actual hasta el final del próximo mes:
const startOfCurrentMonth = new Date(); startOfCurrentMonth.setDate(1); const startOfNextMonth = new Date(); startOfNextMonth.setDate(1); startOfNextMonth.setMonth(startOfNextMonth.getMonth() + 1); const host_count = await PlateModel.find({ $and: [ { postedBy: req.user._id, }, { createdAt: { $gte: startOfCurrentMonth, $lt: startOfNextMonth } }, ], }).count();
Puede utilizar la biblioteca Moment .
const moment = require("moment"); const firstdate = moment().startOf('month').format('DD-MM-YYYY'); console.log(firstdate); const lastdate=moment().endOf('month').format("DD-MM-YYYY"); console.log(lastdate); const host_count = await PlateModel.find({ $and: [ { postedBy: req.user._id, }, { createdAt: { $gte:firstdate, $lt:lastdate } }, ], }).count();