在发出post请求之前等待来自两个文档的数据

t98cgbkg  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(178)

我在node.js/express.js应用程序中加载了一个json文件,如下所示:

{
    "DataSourceID_1":"PWCTRX2",
    "DataSourceID_2":"KALATM1",
     ....
}

我阅读了json文件以便从源模型中找到id,我需要获取其中两个并将其保存在mongodb中的匹配集合(匹配模型)中,但由于某种原因,只添加了一个,我不知道为什么,因为控制台上没有记录任何内容,如何修复?
匹配模型如下所示:

const MatchingSchema = new mongoose.Schema({
  DSID_1: {
    type: mongoose.SchemaTypes.ObjectId,
    ref: "Source",
    required: false,
  },
  DSID_2: {
    type: mongoose.SchemaTypes.ObjectId,
    ref: "Source",
    required: false,
  },
....

源模型如下所示:

....
  DataSource_ID: {
    type: String,
    required: true,
  },
...
app.post("/upload-matching-config", uploads.single("txt"), async (req, res) => {
  // Read the file and send to the callback
  fs.readFile(req.file.path, handleFile);
  let obj;
  let DSID_1;
  let DSID_2;
  let jsonData_1;
  let jsonData_2;
  // Write the callback function
  async function handleFile(err, data) {
    try {
      obj = JSON.parse(data);
      jsonData_1 = await Source.find({
        DataSource_ID: obj.DataSourceID_1,
      });
      jsonData_2 = await Source.find({
        DataSource_ID: obj.DataSourceID_2,
      });
      DSID_2 = jsonData_2._id;
      console.log(jsonData_1);
      DSID_1 = jsonData_1._id;
      console.log(jsonData_2);
    } catch (err) {
      console.log("Something went wrong!" + err);
    }

    const matching = new Matching({
      DSID_1: DSID_1,
      DSID_2: DSID_2,
      DataSourceID_1: obj.DataSourceID_1,
      DataSourceID_2: obj.DataSourceID_2,
      matchingRules: obj.matchingRules,
      MatchingReport_Content: obj.MatchingReport_Content,
      DataSource_1_UnmatchedReport_Content:
        obj.DataSource_1_UnmatchedReport_Content,
      DataSource_2_UnmatchedReport_Content:
        obj.DataSource_2_UnmatchedReport_Content,
    });
    try {
      await matching.save().then((data) => {
        res.send(data);
      });
    } catch (err) {
      console.log(err);
      res.status(400).json({
        message: "DataSources you are trying to match does not exist!",
      });
    }
  }
});

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题