从mongoose中的object中查找匹配的数据



我想从一个对象中获得所有匹配的数据,但我得到一个空数组。

位置表:

const locationSchema = new mongoose.Schema(
{
location: {
name: {
type: String,
unique: true,
required: true,
lowercase: true,
},
subLocation: [String],
},
},
{
timestamps: true,
}
);

,它嵌入在路由表中:

const routeSchema = new mongoose.Schema(
{
location: {
from: {
type: mongoose.Schema.Types.ObjectId,
ref: "Location",
required: true,
},
to: {
type: mongoose.Schema.Types.ObjectId,
ref: "Location",
required: true,
},
},
busId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Bus",
required: true,
},
date: {
type: String,
required: true,
},
departureTime: {
type: Number,
required: true,
},
arrivalTime: {
type: Number,
required: true,
},
},
{
timestamps: true,
}
);

现在我正在运行查询从路由表中获得匹配的数据,但我得到一个空数组。http://127.0.0.1:3000/trips?from=6295871d69217e9c28cf7f19&to=6295874869217e9c28cf7f1c&date=2022-06-02下面是查询:

router.get("/trips", async (req, res) => {
if (!req.query.from || !req.query.to || !req.query.date) {
return res.send({
error: "Please enter the data to get the trip",
});
}
const { from, to, date } = req.query;
const routes = await Route.find({
from,
to,
date,
});

另一个问题:我传递一个Id作为一个值,现在我想传递一个像这样的字符串:from=Mumbai&to=Ahmedabad&date=2022-06-02。怎么做呢?因为每当我这样做时,我都会得到一个强制转换错误

我建议您将位置模式更改为分别具有from和to位置,如下所示。

const locationSchema = new mongoose.Schema(
{
fromLocation: {
name: {
type: String,
unique: true,
required: true,
lowercase: true,
},
subLocation: [String],
},
toLocation: {
name: {
type: String,
unique: true,
required: true,
lowercase: true,
},
subLocation: [String],
},
},
{
timestamps: true,
}
);

因此路由模式应该是这样的

const routeSchema = new mongoose.Schema(
{
location: {
type: mongoose.Schema.Types.ObjectId,
ref: "Location",
required: true,
},
date: {
type:String,
required: true
},
....
....

然后像这样做…

let locations = await Location.find({
'fromLocation.name': from,
'toLocation.name': to,
});

之后

const ids = locations.map(location => location._id)

const routes = await Route.find({$and: [{location : {$in: ids}},{date}]});
const route = routes.find(()=>{
return ([{ date }, { routes }])
});

最新更新