我的mongoose(5.5.15)查询有时能够基于提供的条件查询来“ findById”文档并“选择”子文档。但是,仅一秒钟后(或任何时间量),完全相同的请求无法返回任何内容。 MongoDb文档没有任何变化,因此这一定是我做错了。
我已经使用console.log(nextDeliveryDate)在查询看似失败并且日志的输出似乎相同的时候获取日期对象的输出(当然与前一个的时差除外)。因此,该错误似乎是完全随机且不受控制的。
const today = new Date();
let nextDeliveryDate = new Date();
nextDeliveryDate.setHours(0);
nextDeliveryDate.setMinutes(0);
nextDeliveryDate.setSeconds(0);
if (today.getDay() < 2) {
nextDeliveryDate.setDate(today.getDate() + (2 - today.getDay()));
} else {
nextDeliveryDate.setDate(today.getDate() + (7 - today.getDay()));
}
const result = await Kitchen.findById(req.query.kitchen).select({
deliveries: {
"$elemMatch": {
delivery_date: {
$gte: nextDeliveryDate
}
}
}
}).exec();
// SCHEMA from a different file
const kitchenSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
_created: Date,
_lastModified: {
type: Date,
default: Date.now
},
name: {
type: String,
required: true,
unique: true
},
location: {
street: String,
unit: String,
city: String,
state: String,
zipcode: Number,
latitude: Number,
longitude: Number
},
routes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Routes'
}],
manager: {
type: String
},
employees: [{
type: String
}],
deliveries: [{
_id: mongoose.Schema.Types.ObjectId,
_created: Date,
weekday: Number,
delivery_date: Date,
routes: [{...}],
status: {
type: String,
default: 'preparing'
}
}]
});
因此有时我会得到理想的完美结果(来自数组的正确传递对象),有时却什么也没找到。请帮忙。谢谢。