首页 > 解决方案 > How to set the key of the object from query params in model.find

问题描述

I want to make the key of the object from query params in the model.find method.

I have already tried this:

moongoose.model.find({ req.query.type : req.params.tid})

and this:

let type = req.query.type
moongoose.model.find({type  : req.params.tid})

标签: javascriptnode.js

解决方案


如果要将变量值用作键,则需要使用方括号:

const type = req.query.type;
mongoose.model.find({[type]: req.params.tid});
一个例子:
const key = 'myKey';
const obj = { [key]: 'value' };

console.log(obj);

推荐阅读