无法读取未定义的mongodb的属性“find”

问题描述 投票:0回答:1

我开始在nodejs项目中实现mongoose。我在集合中创建了一个测试记录来测试后面的CRUD操作,我正在尝试测试mongo的find()属性,但我不知道该怎么做。

这是我与猫鼬的联系:

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

};

这是我的架构:

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);

这是我的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)
        }
    }

}

这是它显示的错误:

TypeError: Cannot read property 'find' of undefined

我应该如何创建与 mongo 的连接或查询?

更新

如何使用find()方法获取数据总数?可以吗?

node.js mongodb mongoose mongodb-query
1个回答
1
投票

您只需将模型导入控制器中,然后就可以使用您的查询,例如:

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

}

为了获取结果计数,您可以在查询后使用 .count() 来计算结果:

const comp = await Companies.find({}).count();
© www.soinside.com 2019 - 2024. All rights reserved.