如何使用日期字段添加ToSet [英] How to addToSet with date field
问题描述
我在猫鼬中有以下模型:
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);
每次我使用相同的值运行以下命令时,都会将一个新的子文档添加到 relations
数组中.如果我从 RelationSchema
模式中删除了 createdOn
字段,那么它工作正常.
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}
});
我的问题是:如何使用日期/时间字段addToSet
?
My Question is :
How can I addToSet
with date/time fields ?
推荐答案
要使 $addToSet
不添加元素,该元素必须完全匹配现有元素.createdOn
是当前时间,很容易看出为什么在您的情况下从未发生过.
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.
所以 $addToSet
可以很好地处理带有 Date
字段的元素,但它需要完全匹配,就像任何其他类型一样.
So $addToSet
works fine for elements with Date
fields, but it requires an exact match, just like with any other type.
这篇关于如何使用日期字段添加ToSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!