Home > other >  Cannot read property 'find' of undifined mongodb
Cannot read property 'find' of undifined mongodb

Time:07-02

I am starting to implement mongoose in a nodejs project. I have created a test record in a collection to test the CRUD operations from the back, I am trying to test the find() property of mongo but I am not sure how to do it.

This is my connection to mongoose:

const mongoose = require('mongoose');

const mongoURI: string = "mongodb://localhost:27017"
const mongoDB: string = "testdb"

export const setMongo = async() => {

  try {

    let mongodbURI: string = `${mongoURI}/${mongoDB}`
    await mongoose.connect(mongodbURI);
    
    console.log('conected DB')
    
  } catch (error) {
    console.log('error DB')
  }

};

This is my Schema:

const mongoose = require('mongoose');

const companiesSchema = new mongoose.Schema ({
    name: {
        type: String,
        required: true
    },
    phoneNumber: {
        type: Number,
        required: true,
        unique: true
    }
}, {
    versionKey: false,
    collection: 'companies'
});

module.exports = mongoose.model('Companies', companiesSchema);

This is my resposity.ts:

const companySchema = require("../../schemas/companies")
const db = companySchema.Companies

export class Repository {

    public async getAll(): Promise<any> {        
        try {

            console.log('getAll()')
            const comp = await db.find({});
            console.log(comp)
            
        } catch (error) {
            console.log(error)
        }
    }

}

This is the error it shows:

TypeError: Cannot read property 'find' of undefined

How should I create the connections or queries to mongo?

UPDATE

How can I get the total of the data with the find() method? Is it possible?

CodePudding user response:

you just import your model in your controller and then you can use your query like:

const Companies = require("../../schemas/companies")

export class Repository {

    public async getAll(): Promise<any> {        
        try {

            console.log('getAll()')
            const comp = await Companies.find({});
            console.log(comp)
            
        } catch (error) {
            console.log(error)
        }
    }

}

and for get count of your result you can use .count() after your query to count your result :

const comp = await Companies.find({}).count();
  • Related