簡體   English   中英

"在 Node.js 中使用 Mongoose 從 MongoDB 插入和讀取數據"

[英]Inserting and reading data from MongoDB with Mongoose in Node.js

我正在使用 Mongoose 以相同的方式從 MonoDB 中插入和讀取數據三次,第一次和第二次一切正常,但在第三次嘗試時出現錯誤:

Error: Name [ValidationError] - Message [Station validation failed: ContractId: Path "ContractId" is required.]

異常是在createStations中產生的,Contract.findOne({ Id: c.ContractId Contract.findOne({ Id: c.ContractId }).exec(),的 c.ContractId 肯定不為空。 如果我再次運行 onFileupload,Stations 中的所有數據都將被填充。 所以,我想我在等待/異步/保存/執行方面做錯了什么?

我的客戶架構:

const mongoose = require('mongoose');

const ClientSchema = new mongoose.Schema({
  Id: {
    type: String,
    required: true,
    unique: true,
  },
  Name: {
    type: String,
    required: true,
  },
});

// {
//   Id: '123456',
//   Name: 'Stackoverflow',
//   _id: new ObjectId("61fea3350613880a00a70752"),
//   __v: 0
// }

module.exports = mongoose.model('Client', ClientSchema);

我的合同架構:

const mongoose = require('mongoose');

const ContractSchema = new mongoose.Schema({
  ClientId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Client',
  },
  Id: {
    type: String,
    required: true,
    unique: true,
  },
});

// ClientId: {
//   _id: new ObjectId("61fea3350613880a00a70752"),
//   Id: '123456',
//   Name: 'Stackoverflow',
//   __v: 0
// },
// Id: 'SO_000000',
// _id: new ObjectId("61fea380eabdfd631439e9d5"),
// __v: 0
// }

module.exports = mongoose.model('Contract', ContractSchema);

我的站架構

const mongoose = require('mongoose');

const StationSchema = new mongoose.Schema({
  ContractId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Contract',
    required: true,
  },
  StationId: {
    type: String,
  },
});

module.exports = mongoose.model('Station', StationSchema);

我如何插入和讀取數據:

async function createStations(df) {
  console.debug('createStations');
  df.forEach(async (c) => {
    try {
      const station = await new Station({
        ContractId: await Contract.findOne({ Id: c.ContractId }).exec(),
      }).save();
    } catch (err) {
      logger.error(`Error: Name [${err.name}] - Message [${err.message}]`);
    }
  });
}

async function createContracts(df) {
  console.debug('createContracts');
  df.forEach(async (c) => {
    try {
      const contract = await new Contract({
        ClientId: await Client.findOne({ Id: c.ClientId }).exec(),
        Id: c.ContractId,
      }).save();
    } catch (err) {
      logger.error(`Error: Name [${err.name}] - Message [${err.message}]`);
    }
  });
}

async function createClients(df) {
  console.debug('createClients');
  df.forEach(async (c) => {
    try {
      const client = await new Client({
        Id: c.Id,
        Name: c.Name,
      }).save();
    } catch (err) {
      logger.error(`Error: Name [${err.name}] - Message [${err.message}]`);
    }
  });
}

function onFileupload(req, res) {
  const file = req.files.thumbnail;
  file.mv(file.name, async (err) => {
    if (err) {
      return res.status(500).send(err);
    }
    const workbook = xlsx.readFile(file.name);
    const sheetNames = workbook.SheetNames;
    await createClients(xlsx.utils.sheet_to_json(workbook.Sheets[sheetNames[0]]));
    await createContracts(xlsx.utils.sheet_to_json(workbook.Sheets[sheetNames[1]]));
    await createStations(xlsx.utils.sheet_to_json(workbook.Sheets[sheetNames[2]]));
    return res.status(200);
  });
}

提前致謝

我找到了一種方法,這是我的解決方案:

async function createClients(df) {
  await Promise.all(
    df.map(async (c) => {
      try {
        await new Client({
          Id: c.Id,
          Name: c.Name,
        }).save();
      } catch (err) {
        logger.error(`Error: Name [${err.name}] - Message [${err.message}]`);
      }
    }),
  );
}

暫無
暫無

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

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