Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

findOne.cache is not a function #2

Closed
ajmas opened this issue Sep 23, 2021 · 5 comments
Closed

findOne.cache is not a function #2

ajmas opened this issue Sep 23, 2021 · 5 comments

Comments

@ajmas
Copy link

ajmas commented Sep 23, 2021

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

  • Nodejs: 14.15.1
  • mongoose: 5.9.26
  • mongodb (package): 3.5.9
  • mongodb server: 5.0.2
  • recachegoose: 8.1.0
  • OS: macOS
@aalfiann
Copy link
Owner

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
Copy link
Author

ajmas commented Sep 24, 2021

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
Copy link
Owner

I'll check this..

@aalfiann
Copy link
Owner

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:

  • Mongo Server: 5.0
  • Mongoose: 5.0.1
  • OS: Ubuntu 18

@ajmas
Copy link
Author

ajmas commented Sep 24, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants