简体   繁体   English

Node.js API对于同一请求返回不同的值

[英]Node.js API return different values for the same request

I'm learning to use Node.js + Express to build a REST API. 我正在学习使用Node.js + Express构建REST API。 In this API I have the following method: 在此API中,我具有以下方法:

  apiRouter.route('/training/session/byId/:id_session')
  // ===== GET =======
  .get(function(req, res) {

    //Get the session
    Session.findById(req.params.id_session, function(err, session) {

      //Get an array of exercise associated with the session
      Exercise.find({session: session._id}, function(err, exercise) {
        let movements = [];
        let sets = [];
        let i = exercise.length-1;

        //For every exercise get the movements and the sets
        exercise.forEach(function (ex,index) {
          Movement.findById(ex.movement,function(err,movement){
            if(movement)
              movements.push(movement);

            //***** Here?
            Set.find({exercise: ex}, function (err, set) {
              if(set.length)
                sets.push(set);
              if(index == i){
                res.json({ message: 'ok' ,session,exercise,movements,sets});
              }
            })
          })
        })
      });
    });
  })

The idea is obtain all the session related information from the database. 这个想法是从数据库中获取所有与会话相关的信息。

First: I think that is not the correct way of make multiple querys and return an object with the info of all the querys, but I'm novice with the async working of Node... So what is the correct way to make multiple querys where the data of one query depends of other query? 首先:我认为这不是进行多个查询并返回包含所有查询信息的对象的正确方法,但是我对Node的异步工作还是不熟悉,所以进行多个查询的正确方法是什么?一个查询的数据在哪里取决于其他查询?

Second: In the Front-End (React + Redux) I'm making Ajax request with axios and for the same Ajax request sometimes not all 'sets' are fetched (//***** Here?). 第二:在前端(React + Redux)中,我使用axios发出Ajax请求,对于相同的Ajax请求,有时并非提取所有“集合”(// *****在这里?)。 The problem is in the API? 问题出在API中吗?

Thanks in advance. 提前致谢。

EDIT: DB models 编辑:数据库模型

Session: 会议:

var SessionSchema   = new Schema({
  date: {type: Date, default: Date.now },
  time: Number, //Time in seconds
  user: {required: true, type: mongoose.Schema.Types.ObjectId, ref: 'User'},

});

Exercise: 行使:

var ExerciseSchema   = new Schema({
    session: {type: mongoose.Schema.Types.ObjectId, ref: 'Session'},
    movement: {type: mongoose.Schema.Types.ObjectId, ref: 'Movement'},
  timestamp: {
        type: Date,
        default: Date.now
      }
});

Set: 组:

var SetSchema   = new Schema({
    repetitions: Number,
  weight: Number,
  rest: Number,
  timestamp: {
        type: Date,
        default: Date.now
      },
    exercise : {type: mongoose.Schema.Types.ObjectId, ref: 'Exercise'}

});

Movement: 运动:

var MovementSchema   = new Schema({
    name:  { type: String, required: true, index: true, unique: true },
  material:{ type: String, required: true},
  muscles : [{
    name : { type: String, required: true},
    percentage : { type: Number, required: true}
     }]
});
Set.find({exercise: ex}, function (err, set) {  
if(set.length)
    sets.push(set);      
}).then(function(set){
    if(index == i){
        res.json({ message: 'ok' ,session,exercise,movements,sets});
    }
})

Of course my prev answer wouldn't work. 当然,我的上一个答案是行不通的。 The set query callback would execute after the if(index == i). 设置的查询回调将在if(index == i)之后执行。 Actually I'm not sure this will produce different results from your code. 实际上,我不确定这会与您的代码产生不同的结果。 I've never actually used Mongoose but as far as I know, you can't do joins so nested queries is the way to do it. 我从未真正使用过Mongoose,但据我所知,您无法进行联接,因此嵌套查询是做到这一点的方法。

You might want to consider using promises. 您可能要考虑使用诺言。 Not necessary, but they make your code easier to read and think about: http://eddywashere.com/blog/switching-out-callbacks-with-promises-in-mongoose/ 不必要,但是它们使您的代码更易于阅读和思考: http : //eddywashere.com/blog/switching-out-callbacks-with-promises-in-mongoose/

It might make more sense as well to create a single result object that you build up as the queries return so you end up sending a single JSON object representing your session that looks like: 创建一个随查询返回而建立的单个结果对象也可能更有意义,因此最终将发送一个表示您的会话的JSON对象,如下所示:

{
    exercises: [
                    {
                        sets: [],
                        movements: [],
                    },
                    {
                        sets: [],
                        movements: [],
                    },
                    ...
                ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM