Express服务器GET请求userId

时间:2018-11-28 13:20:14

标签: node.js mongodb express mongoose

我想为taskuser / getallusers?userId =''创建GET API路由。

我想获取分配给特定用户的所有任务。但是,当我测试此呼叫(http://localhost:4000/api/taskuser/getalltasks?userId=5bfe4af425ddde2b04eb19c6)却没有错误吗?

我仍然将所有任务分配给任何用户。有人可以告诉我怎么了吗?

模型任务用户:

const mongoose = require('mongoose');

const TaskuserSchema = new mongoose.Schema({
task_name:{
    type: String,
    required: true,
    minlength: 1,
    unique: true,
},
userId: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
  },
task_category: String,
task_xpreward: Number,
task_completed: Boolean,
task_difficulty: Number, 
task_city : String,
});

Api路线:

router.get('/getalltasks/:userid', cors(),async(req,res) => { // Add /:userid
 var userid = req.params.userid;
 Taskuser.find({ userId: userid}, 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 

 });
});

编辑:新的api路线

2 个答案:

答案 0 :(得分:1)

您应该将代码更新为:

router.get('/getalltasks/:userid', cors(),async(req,res) => { // Add /:userid
var userid = req.params.userid;
Taskuser.find({ userId: userid}, 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 

  });
});

文档:https://mongoosejs.com/docs/api.html#model_Model.find

答案 1 :(得分:0)

将您的api路由文件更改为此:

chart