In db.js
import mongoose from "mongoose";
export function dbConnection() {
try {
mongoose.connect("mongodb://0.0.0.0:27017", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("DB connected successfully ");
} catch (error) {
console.log("Not connected ");
}
}
In Jobmodel.js
import mongoose from "mongoose";
import autoIncrement from "mongoose-auto-increment";
const JobSchema = new mongoose.Schema({
company: {
type: String,
required: true
},
new: {
type: Boolean
},
position: {
type: String,
required: true
},
role: {
type: String,
required: true,
},
postedAt: {
type: String,
}
});
// Apply the auto-increment plugin to your schema
JobSchema.plugin(autoIncrement.plugin, {
model: 'Job',
field: 'id', // The field to auto-increment
startAt: 1, // Start from 1
incrementBy: 1 // Increment by 1
});
const JobModel = mongoose.model('Job', JobSchema);
export default JobModel;
And in index.js main file i have called the dbConnection() function
Then Why am i getting this error in the console?
Note: I have also tried to initialize the autoincrement library before mongoose.connect in db.js file. Like this => autoIncrement.initialize(mongoose.connection);
if (!counterSchema || !IdentityCounter) throw new Error("mongoose-auto-increment has not
been initialized");
^
Error: mongoose-auto-increment has not been initialized
at exports.plugin (G:REACTFRONTEND MENTOR IOJob Listingapinode_modulesmongoose-auto-incrementindex.js:36:49)
at Schema.plugin (G:REACTFRONTEND MENTOR IOJob Listingapinode_modulesmongooselibschema.js:1932:3)
at file:///G:/REACT/FRONTEND%20MENTOR%20IO/Job%20Listing/api/model/Jobmodel.js:28:11
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
2
Answers
I have also tried this approach
Then i get this error
You need to initialize the
mongoose-auto-increment
as the error shows.refs
https://www.npmjs.com/package/mongoose-auto-increment