skip to Main Content

This is my app.js file. Please help me out to connect it with my local database. Sometimes it gets connected to the database and logs to the console but it doesn’t add any collection to the local database.

const mongoose = require('mongoose')

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

async function main() {

  await mongoose.connect("mongodb://localhost:27017/fruitsDB", {
    useNewUrlParser: true,
    useUnifiedTopology: true
  });

  //Creating new schema
  
  const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
  });
  
  const Fruit = mongoose.model("Fruit", fruitSchema);
  
  const fruit = new Fruit ({
    name: "Apple",
    rating: 7,
    review: "Pretty solid"
  });
  
  await fruit.save()
}

2

Answers


  1. Insist localhost use 127.0.0.1:27017 This will work for sure.

    OR
    This happened probably because the MongoDB service isn’t started. Follow the below steps to start it:

    1. Go to Control Panel and click on Administrative Tools.
    2. Double-click on Services. A new window opens up.
    3. Search MongoDB.exe. Right-click on it and select Start
      The server will start. Now execute npm start again and the code might work this time.
    Login or Signup to reply.
  2. You can use mongo connection like this in typescript for ES6.
    Schema like below

    import mongoose from "mongoose"
    
    
    export const RequestLogsSchema = new mongoose.Schema(
      {
        request_id: String,
        ...
      },
      {
        collection: "request_logs"
      }
    )
    

    example connection like below

    import mongoose from 'mongoose'
    import { RequestLogsSchema } from './mongo-schemas/RequestLogsSchema'
    
    
    export class MongoClient {
      mongodb: any
    
      constructor(private host: string) { }
    
      async MongoConnect() {
    
        return new Promise(async (resolve, _reject): Promise<void> => {
    
          console.log('🟡 MongoDB Connecting !')
    
          this.mongodb = await mongoose.connect(this.host).then(() => {
            console.log('🟢 MongoDB Connected !')
            resolve(true)
          }).catch((err) => console.log(err))
    
        })
    
      }
    }
    
    export const schemas = {
      RequestLogsModal: mongoose.model("RequestLogs", RequestLogsSchema),
      ...
    }
    
    new MongoClient('mongodb://username:password@localhost:27017/db_name?authSource=db_name').MongoConnect()
    

    To save your data like

    import { schemas } from '../connections/mongo'
    
    const saver = (data) => {
        const request_logs = new schemas.RequestLogsModal({
          request_id: data.request_id,
          ...
        })
    
        await request_logs.save()
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search