The autoincrement feature does not support the schema.path function

Currently, I am facing an issue while attempting to implement an auto-increment ID field for a person collection in a MongoDB cloud database. The error arises at the line containing

const schemaKey = this._schema.path(this._options.inc_field);
when I include
const AutoIncrement = AutoIncrementFactory(conn2);
. Below is the code snippet:

UPDATE: The error has been resolved, however, the auto-increment feature is still not functioning as expected. The id field does not automatically generate when saving a new person.

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

if (process.argv.length<3) {
  console.log('provide 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()
})

Answer №1

To implement the module, there are 2 ways as explained in the documentation:

  • If you have a single connection to the database, use the following initialization:
const mongoose = require('mongoose')
const AutoIncrement = require('mongoose-sequence')(mongoose);
  • For multiple connections to the database, initialize separately for each connection:
const mongoose = require('mongoose')
const AutoIncrementFactory = require('mongoose-sequence');

const connection = await mongoose.createConnection('mongodb://...');

const AutoIncrement = AutoIncrementFactory(connection);

Your current code combines both methods, choose one approach that suits your setup best.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to load JS or CSS files in EJS, Express, and NodeJS

I'm delving into the world of EJS, Node, and Express (completely new to all three). Below you'll find my ejs file, app.js file, and directory structure. Could someone please guide me on properly setting things up? Appreciate your help in advance. ...

Remove an item from an array within Express using Mongoose

{ "_id": "608c3d353f94ae40aff1dec4", "userId": "608425c08a3f8db8845bee84", "experiences": [ { "designation": "Manager", "_id": "609197056bd0ea09eee94 ...

Access Denied - NodeJS

Currently facing an issue with my MEAN stack application on AWS - Windows. I've set port 3000 for the Node server and IIS is using the default port 80. When trying to retrieve data using Angular via Node, I encounter an error while making a GET reque ...

Having trouble with `npm install socket.io` getting stuck during the node-gyp step

As I wanted to incorporate `socket.io` into my `node.js` application, I opted to utilize `npm` for the installation process. By simply inputting `npm install socket.io -g` in my terminal, I initiated the installation. > <a href="/cdn-cgi/l/email-p ...

Exploring promises with loops and patience?

I created a function that accesses an API and retrieves an array containing 100 objects at once. The getPageData() function works as expected when passing an integer without the loop. However, when attempting to iterate through it, I am not getting any res ...

Do native node.js addons still require HandleScopes to be used?

The Node.js v6.4.0 documentation on Addons outlines a specific pattern that functions must follow. void X(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); ... } In this version, there is no need to instantiat ...

Guide on retrieving the innerHTML of all <a> tags within a specific span class

<span class="mgen"> <a rel="tag">Action</a> <a rel="tag">Adventure</a> <a rel="tag">Apocalypse</a> <a rel="tag">Fantasy</a> <a rel="tag" ...

Issue: Trying to render objects as React children is invalid (object found with keys {_id}). If you intended to display multiple children, use an array instead

My intention in the NextJS application is to retrieve JSON data from my MongoDB database using getInitialProps as shown below: static async getInitialProps(ctx) { const res = await fetch('http://localhost:3000/api/endpoint'); const j ...

How can special characters be decoded in Node.js Express?

I attempted to follow the instructions provided in this resource but I am unable to decode the URI. Can someone guide me on how to proceed? For example, when I input a city like http://localhost:5000/weather?weatherCity=Malmö, the URL transforms into htt ...

Preventing Users from Accessing NodeJS Express Routes: A Guide

Currently, I am working on a React application where I am utilizing Express to handle database queries and other functions. When trying to retrieve data for a specific user through the express routes like so: app.get("/u/:id", function(req, res) { ...

Model calculates product of two columns using Sequelize

Is it possible to multiply the quantity and unit columns from a table using sequelize's findAll method? Products.findAll({ attributes: [ 'id', 'Product', 'Quantity', ' ...

The problem of losing connection with a socket and the process of checking

After successfully developing a chat application using socket and node js, I encountered an issue where after some time interval, a polling error would occur leading to the disconnection of the socket. Screenshot of the error: https://drive.google.com/fil ...

The Access-Control-Allow-Origin error is preventing the Angularjs post request from going through

I am encountering an issue with my index.html file that is sending a post request to localhost:3000/SetUser. The error I keep receiving states XMLHttpRequest cannot load https://localhost:3000/SetUser. No 'Access-Control-Allow-Origin' header is p ...

The test.ts file does not contain any type definitions

While I am able to successfully utilize my types in .ts files, I am facing difficulties in understanding why it's failing in .test.ts files, even though both files are located in the same folder. Check out the code in the .ts file below: https://i.s ...

Displaying Images Containing Umlauts Might Cause Issues

It has come to my attention that none of the images containing characters like ü,ä,ö are loading on my production server. However, everything works perfectly fine when I serve them locally using nodemon + browsersync. What specific settings do I need t ...

Utilizing Object-Oriented Programming to organize and store data within a class object

After successfully running a class to fetch all data and store it in an object, I noticed that the object (AllOptions) is undefined. I have attempted to find a suitable solution but have been unsuccessful. router.get('/:category', (req, res) =& ...

Struggling to merge two variables together and receiving this error message: "mergedObject is not defined."

New to Node.js/Express and trying to combine two objects to save them to a collection. Any advice would be greatly appreciated! Thank you in advance for your time. This is what I've put together, but it's not functioning as expected: app.post( ...

The XML package in Node.js is encountering issues when trying to process keys that contain colons

I'm planning to send an XML response from my Node.js API. Currently, I am utilizing the xml - npm package Here is an example of how I am sending data: res.set('Content-Type', 'text/xml'); let example5 = [ { toys: [ { ...

Logging messages in Node.js using console.log while inside an asynchronous function

Can someone explain why the product data isn't appearing when I try to scrape a website using puppeteer? const puppeteer = require("puppeteer"); (async () => { const browser = await puppeteer.launch({ headless: false }); const page = await br ...

Error: The object identified as #<Object> does not support the 'Router' method in node

Hey there! I've been trying to follow a tutorial on creating Chat Roulette using Node.js, Socket.io, and OpenTok from this link. After successfully installing express, I updated the code in my Package.json file as per the tutorial with the following: ...