簡體   English   中英

Node.js API對於同一請求返回不同的值

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

我正在學習使用Node.js + Express構建REST API。 在此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});
              }
            })
          })
        })
      });
    });
  })

這個想法是從數據庫中獲取所有與會話相關的信息。

首先:我認為這不是進行多個查詢並返回包含所有查詢信息的對象的正確方法,但是我對Node的異步工作還是不熟悉,所以進行多個查詢的正確方法是什么?一個查詢的數據在哪里取決於其他查詢?

第二:在前端(React + Redux)中,我使用axios發出Ajax請求,對於相同的Ajax請求,有時並非提取所有“集合”(// *****在這里?)。 問題出在API中嗎?

提前致謝。

編輯:數據庫模型

會議:

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'},

});

行使:

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
      }
});

組:

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

});

運動:

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});
    }
})

當然,我的上一個答案是行不通的。 設置的查詢回調將在if(index == i)之后執行。 實際上,我不確定這會與您的代碼產生不同的結果。 我從未真正使用過Mongoose,但據我所知,您無法進行聯接,因此嵌套查詢是做到這一點的方法。

您可能要考慮使用諾言。 不必要,但是它們使您的代碼更易於閱讀和思考: http : //eddywashere.com/blog/switching-out-callbacks-with-promises-in-mongoose/

創建一個隨查詢返回而建立的單個結果對象也可能更有意義,因此最終將發送一個表示您的會話的JSON對象,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM