考虑以下对象:
var child = {
title: "Shoes",
active: true,
sort: 1
}
以下更新:
db.Category.update(
{ _id: this._id },
{ $addToSet: { children: child }}, function(error) {
if (error) {
console.log(error.reason);
} else {
console.log("success");
}
}
);
有没有办法在此添加更具体的条件?基本上,我只想要一个项目添加到数组中,如果它不存在,但Mongo通过子项的所有属性来确定它。
如果children.title存在,我基本上希望更新失败,大写,小写等。
所以,如果我有一个文件,如:
{
title: "Clothing",
active: true,
sortorder: 1,
children: [
{
title: "Shoes",
active: true,
sortorder: 1
}
]
}
如果标题:" Shoes"我希望此数组的任何添加都失败。存在......鞋子,鞋子,鞋子,都应该失败。或者,无论这个孩子的其他属性是否不同,例如活动或排序顺序,我希望它仅基于标题失败。
我希望我找不到有条件的方法。
感谢您的帮助。
答案 0 :(得分:0)
正则表达式匹配可以帮助您做到这一点。
var child = {
title: "Shoes",
active: true,
sort: 1
}
方法1:
db.Category.update({
"_id" : this._id,
"children.title" : {
$not : /^shoes$/i
}
}, {
$push : {
children : child
}
}, funcCallback);
方法2:
var title = "Shoes";
var regexp = "^(?!" + title + "$)";
db.Category.update({
"_id" : this._id,
"children.title" : {
$regex : regexp,
$options : "i"
}
}, {
$push : {
children : child
}
}, funcCallback);