Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to check number of documents insert in MongoDB with Mongoose in console.log

I just begin to learn how to use MongoDB and Mongoose, So I try to insert some docs in MongoDB running locally, this is how i do it when I use only MongoDB driver :

const { MongoClient } = require("mongodb");
   const uri = "mongodb://localhost:27017";
   const client = new MongoClient(uri);

   async function run() {
     const dbName = client.db("fruitsDB");
 
     try {
       await client.connect();
       
       // I insert the function to insert the docs here
       await insertMultiDocs(dbName, docs);
    
       // Establish and verify connection
       await client.db("admin").command({ ping: 1 });
       console.log("Connected successfully to server");
     } finally {
       await client.close();
    }
   }
   run().catch(console.dir);

   // below is the docs I want to insert and the function I use like the MongoDB's
   // documentation.
   const docs = [
       { name: "Ananas", rating: 7, review: "nice fruit"},
       { name: "Prune", rating: 8, review: "Kinda good"},
       { name: "Peach", rating: 7, review: "taste great"},
       { name: "Strawberry", rating: 9, review: "great fruit"}
   ];

   async function insertMultiDocs (client, newList) {
     try {
       const insertManyresult = await client.collection("fruits").insertMany(newList);
       let ids = insertManyresult.insertedIds;
       console.log(`${insertManyresult.insertedCount} documents were inserted.`);
       for (let id of Object.values(ids)) {
       console.log(`Inserted a document with id ${id}`);
       }
     } catch(e) {
       console.log(`A MongoBulkWriteException occurred, but there are successfully processed documents.`); 
       let ids = e.result.result.insertedIds;
       for (let id of Object.values(ids)) {
        console.log(`Processed a document with id ${id._id}`);
       }
      console.log(`Number of documents inserted: ${e.result.result.nInserted}`);
     }
   }

Then I get this console.log :

4 documents were inserted.
Inserted a document with id 63051aeb6b883a87e46ea895
Inserted a document with id 63051aeb6b883a87e46ea896
Inserted a document with id 63051aeb6b883a87e46ea897
Inserted a document with id 63051aeb6b883a87e46ea898
Connected successfully to server

Now I want to try to do the same with Mongoose :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const mongoose = require("mongoose");
const { Schema } = mongoose;

main().catch(err => console.log(err));

async function main() {

  try {
    await mongoose.connect("mongodb://localhost:27017/fruitsDB");
    
    const fruitSchema = new Schema({
      name : String,
      rating : Number,
      review : String
    });

    const Fruit = mongoose.model("Fruit", fruitSchema);
    
    // I insert the docs here...
    Fruit.insertMany(docs)
    
  } catch (error) {
    console.log(error);
  }
}

It work, however is there a way to implemente the console.log in Mongoose and loop through each document inserted like the way it did on MongoDB drive ?

>Solution :

insertMany returns the documents that are added to DB post the validation (if any validations are set in place).

You can just .length on it to get the value like this

const insertManyresult = await Fruit.insertMany(docs);

console.log(`${insertManyresult.length} documents were inserted.`);

Since you have access to all the documents. You can perform any operation of choice (loop over every document, get length etc.)

Read more about insertMany here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading