【问题标题】:How do I filter records with a REST API using Express and Mongoose?如何使用 Express 和 Mongoose 使用 REST API 过滤记录?
【发布时间】:2020-01-21 01:36:20
【问题描述】:

我正在使用 Express 和 Mongoose 构建经典的 Todo 服务器。这是我的模型:

import mongoose = require('mongoose');
const autoIncrement = require('mongoose-sequence')(mongoose);

const TodoSchema: mongoose.Schema = new mongoose.Schema({
  todoid: {
    type: Number
  },
  title: {
    type: String,
    required: 'Enter a title'
  },
  note: {
    type: String
  },
  complete: {
    type: Boolean,
    default: false
  },
  editMode: {
    type: Boolean,
    default: false
  }
});

TodoSchema.plugin(autoIncrement, {
  inc_field: 'todoid',
  start_seq: 422
});

export { TodoSchema };

我想处理以下 REST API 查询:

http://localhost:3000/todos?complete=true

我可以FindOne 和那种基本的东西,但我似乎无法弄清楚过滤 GET 调用结果以仅返回已完成的待办事项的代码。

这样做的正确方法是什么?

【问题讨论】:

    标签: rest express mongoose


    【解决方案1】:

    您可以使用find函数根据已完成查询:

    async function getTodohandler(req, res){
      var result = await TodoSchema.find({completed: req.query.completed == "true"})
      return res.send(result)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多