So I'm trying to add a auto-increment id field for a person collection in mongo cloud db, but I get const schemaKey = this._schema.path(this._options.inc_field);
as an error at the line where I've put const AutoIncrement = AutoIncrementFactory(conn2);
. The code is as follows:
EDIT:
Now the error is gone, but the auto-increment still doesnt work as expected, i.e. the id
field is not auto-generated when saving a new person
const mongoose = require('mongoose')
const AutoIncrement = require('mongoose-sequence')(mongoose);
if (process.argv.length<3) {
console.log('give password as argument')
process.exit(1)
}
const password = process.argv[2]
const url =
`mongodb+srv://user:${password}@phonebook.plvo5px.mongodb.net/phonebookApp?retryWrites=true&w=majority`
mongoose.set('strictQuery',false)
mongoose.connect(url)
const personSchema = new mongoose.Schema({
name: String,
number: String,
personId : {
type : Number
}
});
const Person = mongoose.model('Person', personSchema)
personSchema.plugin(AutoIncrement, {inc_field: 'personId'});
const person = new Person({
name: `test2`,
number: `0717323171`
})
person.save().then(result => {
console.log('person saved!')
mongoose.connection.close()
})
The readme shows 2 different ways to include that module:
const mongoose = require('mongoose')
const AutoIncrement = require('mongoose-sequence')(mongoose);
const mongoose = require('mongoose')
const AutoIncrementFactory = require('mongoose-sequence');
const connection = await mongoose.createConnection('mongodb://...');
const AutoIncrement = AutoIncrementFactory(connection);
The code you have is combination of the two, pick only one way.