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 }"}