【发布时间】:2021-06-02 11:52:05
【问题描述】:
我有一个订单模型,我想获取上个月到当前日期创建的所有订单。就像从 2021 年 5 月 1 日到 2021 年 6 月 1 日收到所有订单一样。
我的数据库模式有 {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
上面的代码不起作用。它返回一个空对象。如何获取特定时间范围内的数据?
【问题讨论】:
标签: javascript node.js mongodb date mongoose