K
K
Konstantin2021-05-25 23:00:20
MongoDB
Konstantin, 2021-05-25 23:00:20

How to correctly connect the mongoose-sequence plugin?

I was not satisfied with the id (they were long, and I just needed the numbering 1,2,3) that mongoose generates and I installed mongoose-sequence

As a result, I successfully applied for the user schema:

const mongoose = require('mongoose')
const AutoIncrement = require('mongoose-sequence')(mongoose);


const UserSchema = new mongoose.Schema({
    _id: {
        type: Number,
    }
},
{ _id: false }
)

UserSchema.plugin(AutoIncrement);
module.exports = mongoose.model("User", UserSchema)


And for the user successfully interrupts, the main ID.

I did the same for another model, but it throws an error:

const mongoose = require('mongoose')
const AutoIncrement = require('mongoose-sequence')(mongoose)


const PostSchema = new mongoose.Schema({
 _id: {
   type: Number,
}

},
{ _id: false }
)

PostSchema.plugin(AutoIncrement); 
module.exports = mongoose.model("Post", PostSchema)


That error Error: Counter already defined for field "_id" takes off

But I want to kill id in the Post scheme.
Why can I only override in one schema?

There is another method, add a new field PostSchema.plugin(AutoIncrement, { inc_field : 'id'});
But the task is to kill the main ID.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question