Q:

Auto-increment field in Mongoose

I am trying to create an API using Mongoose and I have a model, where i want to autoincrement the value of the postID.
I have the post schema
const PostSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    postID: {
        type: Number,
        unique: true,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    author: {
        type: Schema.Types.ObjectId,
        ref: 'Author',
        required: true
    },
    dateCreated: {
      type: Date,
      required: true
    },
    lastModified: {
        type: Date,
        required: false
    },
    modifiedBy: {
        type: Schema.Types.ObjectId,
        ref: 'Author',
        required: false
    },
    picture: {
        type: mongoose.SchemaTypes.Url,
        required: false
    }
}, {collection: 'Post'});

and I have created a pre-save hook 
export const PostModel =  mongoose.model('Post', PostSchema);

PostSchema.pre('save', true, async function (next) {
    const post = this;
    post._id = new ObjectID();
    post.dateCreated = new Date();
    try {
        const lastPost = await PostModel.find({postID: {$exists: true}}).sort({id: -1}).limit(1);
        post.postID = lastPost.postID + 1;
    } catch (e){
        console.log('could not take the last post')
    }
    if(post && post.hasOwnProperty('body') && !post.body.isModified){
        return next();
    }
    if(post && post.hasOwnProperty('body') && post.body.isModified){
        post.lastModified = new Date();
        return next();
    }
});

to handle adding the creation date, and autoincrementing the postID. However whenever I am sending a mutation to the API to create the new post, I get an error that 
Post validation failed: dateCreated: Path dateCreated is required., id: Path id is required. 
which means that none of the work handled in the pre-save hook is done. Whenever I am adding some random value to the resolver , the mutation is completed successfully. Any idea why the pre-save isn't working? 
Here is my resolver
module.exports.addPost = async(_,args, req) => {
    const post = new PostModel({
        title: args.post.title,
        body: args.post.body,
        author: new ObjectID(args.post.author),
        picture: args.post.picture
    });
    try {
        return await post.save();
    } catch (e) {
        console.log('Could not save the post');
        console.log(e);
    }
};

and here the mutation
curl 'http://localhost:3001/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: http://localhost:3001' --data-binary '{"query":"mutation($post: PostInput){\n  addPost(post: $post){\n    title\n    body\n    author\n  }\n}","variables":{"post":{"title":"newTitle","body":"Lorem ipsum","author":"5e07e6c07156cb000092ab45","picture":"http://www.example.com"}}}' --compressed

A:

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

