aalfiann / recachegoose

A Mongoose caching module that works exactly how you would expect it to, with the latest version of Mongoose.
https://nodei.co/npm/recachegoose
MIT License
26 stars 14 forks source link

findOne.cache is not a function #2

Closed ajmas closed 3 years ago

ajmas commented 3 years ago

I am having trouble using this, with the following error being generated:

 person_1.default.findOne(...).cache is not a function

The database initialisation code:

let mongooseConnection;

function initQueryCaching (connection: any) {
    // exit early if caching is not to be used
    if (!config.database.cache || !config.database.cache.enabled) {
        logger.info('Database query caching: disabled');
        return;
    }

    const cacheConfig = config.database.cache;

    if (!cacheConfig) {
        throw new Error('No database cache config found');
    }

    cachegoose(connection, cacheConfig);
}

async function initDatabase (): Promise<Mongoose> {
    mongoose.Promise = Promise;

    const dbUrl = config.database.url;
    const options = config.database.options;

    const connection = await mongoose.connect(dbUrl, options);

    // Debugging for testing and development
    if (config.database.debug) {
        if (config.database.debugFile) {
            // We append to the file if it exists
            const stream = fs.createWriteStream(config.database.debugFile, { flags: 'a' });
            mongoose.set('debug', (collectionName, method, query, doc) => {
                stream.write(`${moment.utc().toISOString()} [mongodb] ${collectionName}->${method}->${JSON.stringify(query)}\n`);
            });
        } else {
            mongoose.set('debug', true);
        }
    }

    initQueryCaching (connection);

    // import after connection established
    await import('../models');

    mongooseConnection = connection;

    return connection;
}

Then in use:

const result = await Person.findOne({ email: 'judi@acme.com' }).cache(120);

I do notice the result type for findOne() is DocumentQuery.

Any ideas as to what could be causing this?

Environment

aalfiann commented 3 years ago

have you already test without .cache? is your model query working or not?

The common case is, maybe your model.js is not passing as Model but as Document, so it is better if you show to us your model.js here.

ajmas commented 3 years ago

The query has been working and in production for a good while. It is just the addition of .cache which is proving problematic. The code is as follows:

import mongoose, { Schema, Document } from 'mongoose';

import { createModel } from '../utils/mongoose-utils';
import IPerson from '../interfaces/IPerson';

interface IPersonDB extends IPerson, Document { }

const personSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    title: {
        type: String
    },
    language: {
        type: String,
        default: 'en',
        lowercase: true
    },
    mobile: {
        type: String,
        unique: true,
        sparse: true,
        lowercase: true,
        trim: true,
        index: true,
        set: value => (value === '' ? undefined : value)
    },
    email: {
        type: String,
        unique: true,
        sparse: true,
        lowercase: true,
        trim: true,
        index: true,
        set: value => (value === '' ? undefined : value)
    },
    timezone: String
}, {
    timestamps: true
});

});

export default createModel<IPersonDB>('Person', personSchema);

The source for createModel:

function createModel<T extends Document> (schemaName: string, schema: Schema): Model<T> {
    let model = mongoose.connection.models[schemaName];
    if (!model) {
        model = mongoose.model(schemaName, schema);
    }
    return model;
}
aalfiann commented 3 years ago

I'll check this..

aalfiann commented 3 years ago

I have test this with npm test and also in my production server mongodb version 5, everything running well.

I add some test to make sure Record.findOne is having a function.

As you can see in this image below here.. https://i.imgur.com/uOfXymP.png

See at line 408, there was already function to test get one document. https://i.imgur.com/yNAqwNg.png

And the result is fine.


My Environment:

ajmas commented 3 years ago

I am wondering whether the dynamic import is causing issues with the models and this package. I'll need to investigate.