在我的项目中,我使用猫鼬,并且我想使用select查询从JSON文件中选择特定字段。猫鼬的文档说正确的形式是这样的:
// selecting the `name` and `occupation` fields
query.select('name occupation');
过滤时,我用,
分隔字段,但用(space)
这是我的代码段:
//@desc Get all bootcamps
//@route GET /api/v1/bootcamps
//@access Public
exports.getBootcamps = async (req, res, next) => {
try {
let query;
//Copy req.query
const reqQuery = { ...req.query };
//Fields to exclude
const removeFields = ['select'];
//Loop over the removeFields and delete them from reqQuery
removeFields.forEach(param => delete reqQuery[param]);
//Create query string
let queryStr = JSON.stringify(req.query);
//Create operators($gt, $gte, etc)
const regex = /\b(gt|gte|lt|lte|in)\b/g;
queryStr = queryStr.replace(regex, match => `$${match}`);
//Finding resouce
query = Bootcamp.find(JSON.parse(queryStr));
//Select Fields
if (req.query.select) {
const fields = req.query.select.split(',').join(' ');
console.log(fields);
query = query.select(fields);
}
//Executing query
const bootcamps = await query;
res.status(200).json({
succes: true,
count: bootcamps.length,
data: bootcamps
});
} catch (err) {
return res.status(404).json({ succes: false });
}
};
因此,console.log(fields);
之后,我得到了正确的形式,即:name description
,因为在URL中过滤器是
{{URL}}?select=name,description
但是在将其传递给query = query.select(fields);
之后,我得到了一个200响应的空数组...
我的JSON文件:
{
"_id": "5d713995b721c3bb38c1f5d0",
"name": "Devworks Bootcamp",
"description": "Devworks is a full stack JavaScript Bootcamp located in the heart of Boston that focuses on the technologies you need to get a high paying job as a web developer",
"website": "https://devworks.com",
"phone": "(111) 111-1111",
"email": "enroll@devworks.com",
"address": "233 Bay State Rd Boston MA 02215",
"careers": ["Web Development", "UI/UX", "Business"],
"housing": true,
"jobAssistance": true,
"jobGuarantee": false,
"acceptGi": true
}
编辑:我试图这样写查询:
const bootcamps = await query.select('name description');
当然这次没有使用过滤和 IT WORKED 。我现在不明白...我得到了想要的东西
{
"succes": true,
"count": 4,
"data": [
{
"_id": "5d713a66ec8f2b88b8f830b8",
"name": "ModernTech Bootcamp",
"description": "ModernTech has one goal, and that is to make you a rockstar developer and/or designer with a six figure salary. We teach both development and UI/UX"
},
{
"_id": "5d725a1b7b292f5f8ceff788",
"name": "Devcentral Bootcamp",
"description": "Is coding your passion? Codemasters will give you the skills and the tools to become the best developer possible. We specialize in front end and full stack web development"
},
{
"_id": "5d713995b721c3bb38c1f5d0",
"name": "Devworks Bootcamp",
"description": "Devworks is a full stack JavaScript Bootcamp located in the heart of Boston that focuses on the technologies you need to get a high paying job as a web developer"
},
{
"_id": "5d725a037b292f5f8ceff787",
"name": "Codemasters",
"description": "Is coding your passion? Codemasters will give you the skills and the tools to become the best developer possible. We specialize in full stack web development and data science"
}
]
}