Javascript 如何查询特定时间范围的Mongoose数据库
我有一个订单模型,我想获取上个月到当前日期创建的所有订单。如收到2021年5月1日至2021年6月1日期间的所有订单 我的数据库模式有Javascript 如何查询特定时间范围的Mongoose数据库,javascript,node.js,mongodb,date,mongoose,Javascript,Node.js,Mongodb,Date,Mongoose,我有一个订单模型,我想获取上个月到当前日期创建的所有订单。如收到2021年5月1日至2021年6月1日期间的所有订单 我的数据库模式有{timestamps:true}选项,该选项添加createdAt和updatedAt字段 Order.js const OrderSchema = new mongoose.Schema( { billingAddress: { type: Object, required: true }, deliveryAddress: { type:
{timestamps:true}
选项,该选项添加createdAt
和updatedAt
字段
Order.js
const OrderSchema = new mongoose.Schema(
{
billingAddress: { type: Object, required: true },
deliveryAddress: { type: Object, required: true },
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
seller: {
type: mongoose.Schema.Types.ObjectId,
ref: "Shop",
},
Product: {
product: { type: mongoose.Schema.Types.ObjectId, ref: "Product" },
color: String,
quantity: Number,
},
invoiceId: { type: String, required: true },
paymentIntentId: { type: String, required: true },
totalAmount: { type: Number, required: true },
groupId: { type: String, required: true },
status: {
type: String,
enum: [
"waitingConfirmation",
"confirmed",
"cancelRequest",
"cancelled",
"packing",
"shipped",
"delivered",
],
default: "waitingConfirmation",
},
note: String,
},
{ timestamps: true }
);
当我这样做是为了获取上个月的数据时,它是有效的
const lastMonthOrders = await Order.find({
$and: [
{ seller: req.shop.id },
{
createdAt: {
$gte: new Date(2021, 4, 1),
$lt: new Date(2021, 5, 1),
},
},
],
});
但我希望我的约会是动态的,所以我尝试了这个
let today = new Date();
let lastMonth = new Date(
today.setMonth(today.getMonth() - 1) - 60 * 60 * 1000
);
const lastMonthOrders = await Order.find({
$and: [
{ seller: req.shop.id },
{
createdAt: {
$gte: lastMonth,
$lt: today,
},
},
],
});
我的模型中的时间戳如下所示,其数据类型为日期:
createdAt: 2021-06-02T10:20:26.984+00:00,
updatedAt: 2021-06-02T10:21:28.432+00:00
上面的代码不起作用。它返回一个空对象。如何从特定时间范围获取数据?实际上修改日期,这意味着今天的与上个月的现在是同一个月,两个变量之间只剩下一个小时的间隔
尝试使用下面的代码,尽管有点奇怪:
const lastMonth = new Date();
lastMonth.setMonth(lastMonth.getMonth() - 1);
const today = new Date(new Date() - 60*60*1000);
我推荐图书馆:
虽然我通常也会建议这样做,但如果OP对日期没有进一步的业务,我不建议为此安装软件包。另外,请看这个@GaëtanBoyals,这取决于如果您必须处理日期,请看我总是建议使用moment.js-当然,这只是另一种解决方案。当然,在某些情况下,库几乎是必不可少的。我只是想指出,这并不总是必要的:)注意,这需要当前时间而不是午夜。你可能需要调整时间值。没错,我只是拿了OPs代码,并假设这是他想要的,但它可能非常需要调整
const lastMonthOrders = await Order.find({
$and: [
{ seller: req.shop.id },
{
createdAt: {
$gte: moment().subtract(1, 'month').startOf('month').toDate(),
$lt: moment().startOf('day').toDate(),
// or $lte: moment().subtract(1, 'day').endOf('day').toDate(),
},
},
],
});