Auto-increment field in Mongoose
The snippet above will not work. According to Mongoose's documentation,calling pre or post hooks after compiling a model does not work. So you should move
export const PostModel = mongoose.model('Post', PostSchema);
bellow the pre-hook. Also, as PostModel
isn't defined yet and you want to take the last id of an object inserted to your database, you can move this check to your resolver instead.
let lastPost = await PostModel.find({id: {$exists: true}}).sort({id: -1}).limit(1); // This always returns an array, either empty or with data if(Array.isArray(lastPost) && lastPost.length > 0){ lastPost = lastPost[0] } const post = new PostModel({ ... id: lastPost['id'] + 1 ... }); if(Array.isArray(lastPost) && lastPost.length === 0) { post.id = 0; // If this lastPost is an empty array and you try to access the id property // you will get an error that NaN to Int conversion failed }
Hope this helps