我正在利用MongoDB和Mongoose构建汽车API。我想创建一个端点,该端点使我可以基于传递给req.query的搜索词来查询任何字段。我有两个要连接到我的汽车模型的模型(类别和制造商)。到目前为止,我可以利用Mongoose的填充方法获取所有结果。但是,当我尝试查询时,被引用的字段返回null。
此外,我不确定在填充两个字段(类别和品牌)时如何查询所有字段。
是否存在一种更好的方法来填充每个发现的类别和品牌?有没有更好的方法来搜索集合中的所有字段?
下面的示例代码:
-型号- 汽车
const carSchema = mongoose.Schema({
make: {
type: mongoose.Schema.Types.ObjectId,required: true,ref: 'Make'
},model: {
type: String,trim: true,required: true
},description: {
type: String,year: {
type: Number,min: 1900,max: 2100
},categories: [{
type: {
type: mongoose.Schema.Types.ObjectId,ref: 'Category'
}
}],...
}]
},{
timestamps: true
})
const Car = mongoose.model('Car',carSchema)
module.exports = Car
类别
const categorySchema = mongoose.Schema({
type: {
type: String,unique: true
}
})
const Category = mongoose.model('Category',categorySchema)
module.exports = Category
制造
const makeSchema = mongoose.Schema({
name: {
type: String,unique: true
}
})
const Make = mongoose.model('Make',makeSchema)
module.exports = Make
-汽车路线-
...
router.get('/cars/:id',async (req,res) => {
const _id = req.params.id
try {
const car = await Car.findOne({ _id })
if (!car) {
return res.status(404).send()
}
res.status(200).send(car)
} catch (e) {
res.status(500).send(e)
}
})
router.get('/cars',res,next) => {
const match = {}
const sort = {}
if (req.query.make) {
match.make = { "$regex": req.query.make,"$options": "i"}
}
try {
console.log(match)
const cars = await Car.find({})
.populate({
path: 'make',select: 'name',match
})
.populate({
path: 'categories.type',model: 'Category',select: 'type _id'
})
res.send(cars)
} catch(e) {
console.log(e.message)
res.status(500).send(e)
}
})
...
module.exports = router
-输出- 通过查询时(/ cars?make = koenigsegg)
[
{
"_id": "RANDOMID","make": "null","model": "360 Modena","description": "Testing 66","year": 2015,"categories": [
{
"_id": "5dcdb6e8fa88224721a0711c","type": {
"_id": "IDOFHYPERCARINCATEGORYCOLLECTION","type": "Hyper"
}
},{
"_id": "5dcdb6e8fa88224721a0711b","type": {
"_id": "IDOFSUPERCARINCATEGORYCOLLECTION","type": "Super"
}
}
],... OTHER FIELDS HERE ...
"createdAt": "2019-11-14T20:19:52.248Z","updatedAt": "2019-11-14T20:19:52.248Z","__v": 0
},.. OTHER RECORDS HERE ...
]
未通过查询时(/ cars)=
[
{
"_id": "RANDOMID","make": "IDOFFERRARIInmAKECOLLECTION",.. OTHER RECORDS HERE ...
]