I'm developing a chat system with typescript and mongodb (using mongoose) When creating new message I get the following error:
E11000 duplicate key error collection: test.messages index: user.username_1 dup key: { user.username: null }
I'm using reference for the user in the messages collection and I don't understand where this error is coming from.
Schema:
const user = new Schema({
username: { type: String, unique: true, required: true },
email: { type: String, unique: true, required: true },
password: { type: String, required: true}
});
const message = new Schema({
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true},
message: { type: String, required: true},
timestamp: { type: Date, default: Date.now }
});
export const User = model('User', user);
export const Message = model('Message', message);
user.ts (model file)
export class MUser {
readonly _id: string;
readonly username: string;
readonly email: string;
readonly password: string;
}
message.ts (model file)
export class MMessage {
readonly userId: string;
readonly message: string;
readonly timestamp: Date;
}
function that I use to create the document and return the error:
async createMessage(user: MUser, msg: string) {
await Message.create({userId: user._id, message: msg});
}
I'm not considering the userId
to be unique.
What am I missing here?
Thanks!
CodePudding user response:
Drop the collection and try with new schema it should work.