1
const ReviewSchema = new mongoose.Schema({
    "blog_id": {type: Number, required: true, unique: true},
    ratings: [{
        "user_id": {type: String, required: true, unique: true},
        "rating": {type: Number, required: true}
    }]
})

I have this schema I want when the user gives the same blog id and user id then it gives should give the error and when the user gives a different blog id but has a user id that is already present in another document so it does not give the error but user-id should unique in rating array of object.

{ 
    "_id" : ObjectId("6150837133d7021b186e4665"), 
    "blog_id" : 1, 
    "ratings" : [
        {
            "_id" : ObjectId("6150837133d7021b186e4666"), 
            "user_id" : "2", 
            "rating" : 4
        }
    ], 
    "__v" : 0
}
{ 
    "_id" : ObjectId("6150839933d7021b186e466b"), 
    "blog_id" : 2, 
    "ratings" : [
        {
            "_id" : ObjectId("6150837133d7021b186e4666"), 
            "user_id" : "2", 
            "rating" : 4
        }
    ], 
    "__v" : 0
}

But when I create a unique user_id so it checks for whole collections.

Aman Gupta
  • 45
  • 5
  • Does this answer your question? [MongoDB: Unique index on array element's property](https://stackoverflow.com/questions/6743849/mongodb-unique-index-on-array-elements-property) – Joe Sep 27 '21 at 18:38

1 Answers1

0

I think you should have used the npm package uniqid , to generate a new id for your objects in rating array