'How to create unique index for virtual populated fields in mongodb

I'm trying to create a forum website using mongodb(mongoose)/express/node and up until now I have created 2 models, the User model and the Post model, and the problem is that I want the user to create as much posts as he/she wants however I want the post to be Unique ONLY to the same user based on the slug/title of the post, which means that the user can't create the same post with the same slug/title.

For example: assume we have 2 users in the database, John and Sarah. If John created a post with the title:'best programming languages to learn in 2022' then John himself shouldn't be able to create that post again with same title however Sarah should be able to do that.

User model:

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        unique: true,
        required: [true, 'A user must have a username']

    }, {
    toJSON: { virtuals: true },
    toObject: { virtuals: true }
});

userSchema.virtual('posts', {
    ref: 'Post',
    foreignField: 'user',
    localField: '_id'
})

const User = mongoose.model('User', userSchema);
module.exports = User;

As you can see from the User model, that the posts are virtually populated so they are Not stored on the user document to save on performance.

Post model

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: [true, 'A post must have a title'],
    },
    user: {
        type: mongoose.Schema.ObjectId,
        ref: 'User',
        maxlength: [1, 'A post can\'t have more that one user'],
        minlength: [1, 'A post must have at least one user'],
        required: [true, 'A post must have a user']
    }
    
}, {
    timestamps: true
});

const Post = mongoose.model('Post', postSchema);
module.exports = Post;

The user is referenced in the post model since a post can't have one author.

So what is the best way to do it? if I can use indexes in this situation, how?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source