ramiel/mongoose-sequence

Hang

andersnm opened this issue · 2 comments

Hi, the following program hangs in the call to collection.create(). Not sure what I am doing wrong. It "works" if uncommenting the line with AutoIncrement:

/*
  "dependencies": {
    "mongoose": "^5.5.15",
    "mongoose-sequence": "^5.0.1"
  }
*/
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const AutoIncrement = require('mongoose-sequence')(mongoose);

const TestSchema = new Schema({
    subject: { type: String, required: true },
});

TestSchema.plugin(AutoIncrement, { inc_field: 'testCode' } );

async function oo() {
    const client = await mongoose.createConnection('mongodb://localhost/MONGOOSESEQUENCE');
    const collection = client.model('test', TestSchema);
    // Never returns:
    const result = await collection.create([{
        subject: "subject",
    }]);

    await client.close();
}

oo();

Hello, this is definitely an issue. The problem is that the plugin factory needs the current connection to be able to create an internal collection, the one where the increments are stored. Since you use createConnection, the default connection of mongoose is not defined and that collection is never created. As a temporary workaround you can use mongoose.connect instead of mongoose.createConnection. Meanwhile I'll fix this bug

@andersnm the new version 5.1.0 fix the problem. You must change your code to pass your connection instead of the entire mongoose library.

/*
  "dependencies": {
    "mongoose": "^5.5.15",
    "mongoose-sequence": "^5.1.0"   <------------- Update your dependency
  }
*/


const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const AutoIncrementFactory = require('mongoose-sequence'); // <------- Normal require

async function oo() {
    const client = await mongoose.createConnection('mongodb://localhost/MONGOOSESEQUENCE');

    // Here you pass the connection to get the plugin
    const AutoIncrement = AutoIncrementFactory(client);

    const TestSchema = new Schema({
       subject: { type: String, required: true },
    });

    TestSchema.plugin(AutoIncrement, { inc_field: 'testCode' } );
    

    const collection = client.model('test', TestSchema);
    const result = await collection.create([{
        subject: "subject",
    }]);

    await client.close();
}

oo();

Let me know if this works for you