0
votes

I was designing a schema for a simple gaming platform where the developers can deploy their games and sell them. I have tried to create the whole schema as shown below:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

module.exports = mongoose.model('User', new Schema({

username: { type: String, required: true, unique: true, trim: true },

firstname: { type: String, required: true, trim: true },

password: { type: String, required: true, trim: true },

gameDetails: { type: mongoose.Schema.Types.ObjectId, ref: 'Game' },


 }));

The schema for game collection is given below

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

module.exports = mongoose.model('Game', new Schema({

_id: { type: string, unique: true, trim: true, required: true },

description: { type: String, trim: true },

price: { type: Number, required: true, trim: true },

}));

I was trying to insert a user without having the need to specify his gameDetails beforehand.The first insertion works properly,but from the second insertion without specifying the gameDetails,it is showing duplicate key error because the _id property in Game collection is set as unique and in the previous insertion a Null value was added since it was not given in the first insertion.Can you give me a solution to overcome this? The error was

{"name":"MongoError","message":"E11000 duplicate key error collection: admin.users index: gamedetails.gameid_1 dup key: { : null }","driver":true,"index":0,"code":11000,"errmsg":"E11000 duplicate key error collection: admin.users index: gamedetails.gameid_1 dup key: { : null }"}

2

2 Answers

0
votes

You can use partial index something like this:

username: {
type: String, trim: true, index: {
  unique: true,
  partialFilterExpression: {username: {$type: 'string'}}
}}
0
votes

Mongo automatically creates indexes for sub documents that are provided as references in schema definition.

To check the indexes that are created use :

db.foo.getIndexes()

This command will show the indexes are created on a collection. For your example you will have something like

[
    {
        "v" : 1,
        "gameDetails" : {
            "_id" : 1
        },

    }
]

So that is the reason of the error. For solving you can make a dummy data in games collection and provide the _id value to gameDetails key of User collection.