5

I have following model in mongoose :

var RelationSchema = new Schema({
  user : {type:ObjectId, ref:'users'}
  , type : String
  , remarks : String
  , createdOn : {type:Date, default:Date.now}
}, {_id:false});

var UserRelationSchema = new Schema({
  user : {type:ObjectId, ref:'users'}
  , relations : [RelationSchema]
});

var UserRelation = mongoose.model('user_relations', UserRelationSchema);

Each time I run the following command with same values a new sub-document is being added to the relations array. If I removed createdOn field from the RelationSchema schema then it works fine.

UserRelation.update(
{"user":<ObjectId>} 
, {
    $addToSet: {
       "relations": {"user":<ObjectId>,"type":<String>}
    }
, {upsert:true}
});

My Question is : How can I addToSet with date/time fields ?

Lekhnath
  • 4,532
  • 6
  • 36
  • 62

1 Answers1

1

For $addToSet to not add an element, the element must completely match an existing element. With createdOn being the current time it's easy to see why that never happens in your case.

So $addToSet works fine for elements with Date fields, but it requires an exact match, just like with any other type.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471