node.js - 我如何过滤来自express服务器和nodejs的GET查询

标签 node.js mongodb express mongoose mean-stack

我想创建一个 GET 路由来获取我的所有任务,但只获取 task_completed 属性 bool 值“false”的任务。

现有路线:

router.get('/getalltasks', cors(), async(req, res) => {
Task.find(function(err, tasks) {

// if there is an error retrieving, send the error. 
                // nothing after res.send(err) will execute
if (err)
    res.send(err);


res.json(tasks); // return all tasks that are in JSON format 

  });
});

Mongoos架构:

const mongoose = require('mongoose');

const TaskSchema = new mongoose.Schema({
task_name:{
    type: String,
    required: true,
    minlength: 1,
    unique: true,
},
task_category: String,
task_xpreward: Number,
task_completed: Boolean,
task_difficulty: Number,    //1 = Easy, 2 = Medium, 3 = Hard, 4 = Very Hard, 5 = Impossible
task_city : String,
});

 //sommige variabelen kunnen opgedeeld worden in 2de schema met relatie 
module.exports = mongoose.model('Task', TaskSchema);

如何在现有代码中实现此功能?

最佳答案

因此,如果您想要一项具有 task_completed: false 属性的任务:

编辑:捕获错误:

router.get('/getalltasks', cors(), async(req, res) => {
let task;
try{
task = await Task.findOne({task_completed: false});
   }catche (e){
    console.log(`Err: ${e}`);
   }
 res.json(task);
}

如果您想要所有带有 task_completed: false 的任务:

router.get('/getalltasks', cors(), async(req, res) => {
const tasks = await Task.find({task_completed: false});
res.json(tasks);
}

关于node.js - 我如何过滤来自express服务器和nodejs的GET查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53461872/

相关文章:

node.js - SequelizeInstance 对象未在 Express Handlebars View 中呈现(NodeJS、Express)

mysql - 在 node.js 中使 MySQL 的 ORDER BY 动态化

javascript - Socket.io 和 Node.Js 多服务器

Javascript 包含方法不适用于 MongoDB ID

mongodb - 在 MongoDB 中是否有命名集合的约定?

mongodb - NodeJS Mongoose 数据库随机访问不返回结果

javascript - 将 POST react 到 Node 服务器并处理 JSON 响应

javascript - 使用 res.send 表达 app.param 问题

node.js - NodeJs中单线程和非阻塞I/O操作有什么区别?

php - node.js 和 reactjs 作为 php 模板渲染服务是个好主意吗?