Home > Software engineering >  Mongoose is not connecting to local database
Mongoose is not connecting to local database

Time:10-17

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()
}

CodePudding user response:

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.

CodePudding user response:

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('           
  • Related