I am getting the following error when trying to create a document in a collection.
MongoServerError: E11000 duplicate key error collection: stock-trading-system-db.trades index: user_id_1 dup key: { user_id: ObjectId('6266de71b90b594dab9037f3') }
Here is my schema:
const tradeSchema = new mongoose.Schema({
user_id: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
stock_id: {
type: Schema.Types.ObjectId,
ref: 'Stock',
required: true
},
stock_amount: {
type: Number,
required: true
},
stock_value: {
type: Number,
required: true
},
time_of_trade: {
type: Date,
required: true,
default: new Date()
},
trade_status: {
type: String,
enum: ['Approved', 'Declined', 'Pending'],
required: true,
default: 'Pending'
}
}, { collection: 'trades' })
I don't want user_id and stock_id to be unique, i just want it to check that those ObjectIDs exist in their respective collections before making the trade document. How do i achieve this?
CodePudding user response:
You can do this by verifying the id's of user and stock in the api request before creating a new trade document.
An example api request=>
I'm assuming you're using express.
const {user_id, stock_id}=req.body;
// I'm using countDocuments as it only returns a number. If you need the info // of user then use findById()
// If you've a large collection, then use estimateDocuments()
// https://mongoosejs.com/docs/api.html#model_Model.count
const user=await User.countDocuments({_id:user_id});
if(user===0)return res.status(404).send("Send some response here")
// DO THE SAME FOR STOCK.
// After checking both, then you can create Trade document.
Also, in your Trade model, you are using new mongoose.Schema, but inside your the actual model you've typed Schema.Types.ObjectId
Make sure you've destructured Schema property from mongoose.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const tradeSchema = new Schema
// I Dont think you'll need to add {collection:trades} in second parameter.
CodePudding user response:
It looks like a collection saves the schema that is defined in mongoose, and even if you change the schema, the unique values will stay the same inside the collection.
So even though i had removed
unique: true;
from my mongoose schema, it hadn't removed this from the collection in my DB.
Therefore the solution to this is to delete the collection and recreate it.