Posts

Showing posts from October, 2021

Mongoose

  const mongoose = require ( "mongoose" ); mongoose . connect ( "mongodb://localhost:27017/fruitsDB" ); const fruitSchema = new mongoose . Schema ({     name : {         type : String ,         required : true ,     },     rating : {         type : Number ,         min : 1 ,         max : 10     },     sweet : Number }); const Fruit = mongoose . model ( "Fruit" , fruitSchema ); // CREATE const peach = new Fruit ({                             name : "Peaches" ,                             rating : 7 ,                             sweet : 4                         }...

writing data to a database using mongo driver

const MongoClient = require ( "mongodb" ). MongoClient ; // Replace the uri string with your MongoDB deployment's connection string. const url = "mongodb://localhost:27017" ; const client = new MongoClient ( url ); async function run () {   try {     await client . connect ();     const dbName = "newFruits"     const database = client . db ( dbName );     const foods = database . collection ( "fruits" );     // create an array of documents to insert     const docs = [       { name : "watermelon" , healthy : true , rating : 5 },       { name : "mushroom " , healthy : true , rating : 2 },       { name : "mango" , healthy : true , rating : 4 }     ];     // this option prevents additional documents from being inserted if one fails     const options = { ordered : true };         const result = await f...

To read data from database using mongo driver

  const MongoClient = require ( "mongodb" ). MongoClient ; // Replace the uri string with your MongoDB deployment's connection string. const url = "mongodb://localhost:27017" ; const client = new MongoClient ( url ); async function run () {   try {     await client . connect ();         const cursor = client . db ( "newFruits" ). collection ( "fruits" ). find ({});     const results = await cursor . toArray ();     if ( results . length > 0 ) {         console . log ( `Found listing(s)` );         results . forEach (( result , i ) => {                         console . log ( `$_id: ${ result . _id } name: ${ result . name } review: ${ result . rating } ` );                            });     } else {       ...