Jes*_*est 2 rest mongoose mongodb node.js express
我有一个简单的REST API,我想在特定端点上实现过滤。
想象一下,我有一个这样的端点:
localhost:5000/api/items?color="red"
Run Code Online (Sandbox Code Playgroud)
哪个处理这样的请求:
const items = await Items.find({color: req.query.color})
Run Code Online (Sandbox Code Playgroud)
color
存在该参数时,此方法有效。但是,如果color
省略该参数,则查询将搜索color
is 为的项目undefined
。这不是我所需要的行为。
就我而言,我想添加多个过滤器参数,如果它们不存在,将被忽略。我是否必须为每种情况创建一个单独的查询,或者是否可以告诉Mongoose color
如果该字段为null或未定义,则不要搜索该字段(在这种情况下)?
小智 5
您可以使用“ 解构分配 ” 在req.query中解压缩变量。
const { color } = req.query;
if(color) {
const items = await Items.find({ color })
}
Run Code Online (Sandbox Code Playgroud)
如果您有多个过滤器,则可以使用上面的变量。例如,您可能具有color
和type
参数。这样,您可以构建一个对象以传递给find方法。
const { color, type } = req.query;
let query = {};
if(color) {
query.color = color;
}
if(type) {
query.type = type;
}
const items = await Items.find(query);
Run Code Online (Sandbox Code Playgroud)
如果color
还是type
不是原来的查询,他们将是不确定的或falsy等都将跳过if语句该参数。希望它能起作用!
我只是遇到了同样的问题,如果您使用的是ES6支持的节点版本,则应该可以使用传播。它会自动处理未定义的
var filters = {
colour: "red",
size: undefined
}
Items.find({...filters})
// only colour is defined, so it becomes
Items.find({colour:"red"})
Run Code Online (Sandbox Code Playgroud)
注意如果您使用的是Babel。您可能需要先定义一个对象。
var query = {...filters}
Items.find(query)
Run Code Online (Sandbox Code Playgroud)
我也有这个问题。这是我的解决方案:
在连接设置中添加ignoreUndefined
我正在使用nestjs
MongooseModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
uri: configService.get<string>('MONGO_URI'),
useCreateIndex: true,
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true,
ignoreUndefined: true, // add this to the option
connectionFactory: (connection) => {
connection.plugin(require('mongoose-autopopulate'));
return connection;
},
})
Run Code Online (Sandbox Code Playgroud)
Mongoose: entry.find({ field: undefined })
Run Code Online (Sandbox Code Playgroud)