'Mongoose data Writing issue in Javascript

Just started with a javascript couple of days back. I am trying to use MongoDB with mongoose to write the data but it is not writing even though the connection is established. I would really appreciate it if you can help me point out what I am missing here.

dbtest.js - module to create connection

require("dotenv").config();
const mongoose = require("mongoose");
const Block = require("./model/blockSchema");
const connectDB = async () => {
  try {
    await mongoose.connect(process.env.DATABASE_URI, {
      useUnifiedTopology: true,
      useNewUrlParser: true,
    });
    console.log("CONNECTED to MONGODB DATABASE");
  } catch (err) {
    console.error(err);
  }
};

module.exports = connectDB;

blockchain.js Even though I have verified the connection before calling the main method, it looks like the connection is not available to class methods.

require("dotenv").config();
const { hash256 } = require("../util/util");
const block = require("./block");
const blockchain = require("./blockHeader");
const Block = require("../database/model/blockSchema");
const { mongoose } = require("mongoose");
const connect = require("../database/dbtest");

VERSION = 1;
const ZERO_HASH = String("0").padStart(64, "0");

// Create connection
connect();

class Blockchain {
  GenesisBlock() {
    try {
      const BlockHeight = 0;
      const prevBlockHash = ZERO_HASH;
      this.addBlock(BlockHeight, prevBlockHash);
    } catch (err) {
      console.log(`Error in Genesis Blockchain Function \n ${err}`);
    }
  }

  addBlock(BlockHeight, prevBlockHash) {
    let timestamp = Date.now();
    let Transaction = `Codies Alert sent ${BlockHeight} to Anni`;
    let merkleRoot = hash256(Transaction);
    let bits = "ffff001f";
    let blockHeader = new blockchain.BlockHeader(
      VERSION,
      prevBlockHash,
      merkleRoot,
      timestamp,
      bits
    );
    //Mine a Block 
    blockHeader.mine();

    // Create Schema Instance to Write the data 
    let BlockObj = new Block({
      Height: BlockHeight,
      BlockSize: 1,
      blockHeader: {
        version: 1,
        prevBlockHash: "00000",
        timestamp: timestamp,
        bits: bits,
        nonce: blockHeader.nonce,
        blockHash: blockHeader.blockhash,
      },
      TxCount: 1,
      Transactions: Transaction,
    });

    // Mongoose Schema, Write data
    BlockObj.save((err) => {
      if (err) return console.log(`Error while Writing the Block ${err}`);
      console.log(`Block Written Successfully!!!!!!!`);
    });

    this.chain = new block.Block(BlockHeight, 1, blockHeader, 1, Transaction);

    console.log(BlockObj);
  }

  // Main Function to trigger the process
  main() {
    this.chain = "";
    this.GenesisBlock();

    while (true) {
      let lastBlock = this.chain;
      let Blockheight = lastBlock.Height + 1;
      let prevBlockHash = lastBlock.BlockHeader.blockhash;
      this.addBlock(Blockheight, prevBlockHash);
    }
  }
}

mongoose.connection.once("open", async () => {
  console.log("Connection Verified and ready to write data");
  // Create an instance and call the main method
  const blockchain = new Blockchain();
  blockchain.main();
});

Issue was due to async/await. Here is the updated code that works.

require("dotenv").config();
const { hash256 } = require("../util/util");
const block = require("./block");
const blockchain = require("./blockHeader");
const Block = require("../database/model/blockSchema");
const connect = require("../database/dbtest");
const getLastBlock = require("../database/read");

VERSION = 1;
const ZERO_HASH = String("0").padStart(64, "0");

let mongoose = "";

class Blockchain {
  async GenesisBlock() {
    try {
      console.log(mongoose.connection.readyState);
      const BlockHeight = 0;
      const prevBlockHash = ZERO_HASH;
      await this.addBlock(BlockHeight, prevBlockHash);
    } catch (err) {
      console.log(`Error in Genesis Blockchain Function \n ${err}`);
    }
  }

  async addBlock(BlockHeight, prevBlockHash) {
    let timestamp = Date.now();
    let Transaction = `Codies Alert sent ${BlockHeight} to Anni Maan`;
    let merkleRoot = hash256(Transaction);
    let bits = "ffff001f";
    let blockHeader = new blockchain.BlockHeader(
      VERSION,
      prevBlockHash,
      merkleRoot,
      timestamp,
      bits
    );
    blockHeader.mine();

    let BlockObj = {
      Height: BlockHeight,
      BlockSize: 1,
      blockHeader: {
        version: 1,
        prevBlockHash: blockHeader.prevBlockhash,
        merkleroot: merkleRoot,
        timestamp: timestamp,
        bits: bits,
        nonce: blockHeader.nonce,
        blockhash: blockHeader.blockhash,
      },
      TxCount: 1,
      Transactions: Transaction,
    };

    // Mongoose Schema, Write data
    try {
      await new Block(BlockObj).save();
      console.log(BlockObj);
      console.log("Block Written Successfully");
      this.chain = new block.Block(BlockHeight, 1, blockHeader, 1, Transaction);
    } catch (err) {
      console.log(`Error in addBlock Function \n ${err}`);
    }
  }

  // Main Function to trigger the process
  async main() {
    const lastBlock = await getLastBlock.main(true);
    console.log(lastBlock[0]);
    this.chain = lastBlock[0];

    if (!this.chain) {
      await this.GenesisBlock();
    }

    while (true) {
      console.log(mongoose.connection.readyState);
      let lastBlock = this.chain;
      let Blockheight = lastBlock.Height + 1;
      let prevBlockHash = lastBlock.blockHeader.blockhash;
      await this.addBlock(Blockheight, prevBlockHash);
    }
  }
}

const createConnection = async () => {
  try {
    mongoose = await connect();
    const blockchain = new Blockchain();
    blockchain.main();
  } catch (err) {
    console.log("Error while con", err);
  }
};

createConnection();



Solution 1:[1]

The issue in your code is due to the asynchronous programming, whenever you make a db call it is an asynchronous request and you will need to use async-await or Promises to make it work. In your previous code you haven't used async await thats why your data is not getting written into the db.

You can learn about async await here link and about promises here.

Please go through it, promises are the core concept of js and you will definitely need it if you are using node js.

Also try to learn about synchronous and asynchronous from here, these are really necessary and base of node js.

All these db calls needs to call with promises or async await to make it work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashishssoni