Javascript 填充字段上的FeatherJS查询
我用下面的钩子填充字段Javascript 填充字段上的FeatherJS查询,javascript,node.js,feathersjs,Javascript,Node.js,Feathersjs,我用下面的钩子填充字段 const populate = (context) => { const stringList = ['vehicleId', 'userId', 'locationId']; context.params.query['$populate'] = { path: `${stringList.join(' ')}`, // level one } return context; } 但是,我无法对这些填充的值进行嵌套查询,例如 { _id: 1, price:
const populate = (context) => {
const stringList = ['vehicleId', 'userId', 'locationId'];
context.params.query['$populate'] = {
path: `${stringList.join(' ')}`, // level one
}
return context;
}
但是,我无法对这些填充的值进行嵌套查询,例如
{
_id: 1,
price: 500,
vehicleId: {
_id: 100,
name: "BMW",
color: "black
}
}
虽然我可以查询价格,但无法查询颜色=黑色。
到目前为止,我找到的唯一解决方案是执行自定义数据库查询以获取所有ID,并查询ID
// Grabs query like vehicle.color and stores it in array like
// [ {"vehicle.color": "black" } ]
const vehicleQueries = reduce(
query,
(acc, value, key) => {
if (key && key.includes('vehicle') && acc) {
return [...acc, { [key]: value }];
}
context.params.query = omit(context.params.query, key);
return acc;
},
[]
);
// Go over all vehicle queries
// Perform a database request to get all vehicle _ids that have color: black
const vehicleIds = await reduce(
vehicleQueries,
async (acc, queryObject) => {
acc = await acc;
const key = Object.keys(queryObject)[0];
context.params.query = omit(context.params.query, key);
const value = Object.values(queryObject)[0];
const vehicles = await context.app
.service('vehicles')
.Model.find({ [key.replace('vehicle.', '')]: value });
if (!isEmpty(vehicles) && acc) {
const ids = vehicles.map((vehicle) => vehicle._id);
return [...acc, ...ids];
}
return acc;
},
[]
);
// add default Feather's $in query, to only show vehicles of that id
if (!isEmpty(vehicleIds)) {
context.params.query = {
...context.params.query,
vehicleId: { $in: vehicleIds },
};
}