在对象数组上使用Mongoose/MongoDB $ addToSet功能 [英] Using Mongoose / MongoDB $addToSet functionality on array of objects

查看:384
本文介绍了在对象数组上使用Mongoose/MongoDB $ addToSet功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在猫鼬模式中具有此数组属性(文章"):

say I have this array property ('articles') on a Mongoose schema:

articles: [ 

 {
  kind: 'bear',
  hashtag: 'foo'    
 },

 {
  kind: 'llama',
  hashtag: 'baz',
  },

 {
  kind: 'sheep',
  hashtag: 'bar',
  }

]

我怎么使用

$ addToSet https://docs.mongodb.org/manual/reference /operator/update/addToSet/

通过检查主题标签的值以查看其是否唯一来添加到该数组中?

to add to this array by checking the value of hashtag to see if it's unique?

例如,如果我要将以下对象添加到上述数组中,则希望Mongo将其重复"删除:

For example, if I want to add the following object to the above array, I want Mongo to 'reject' it as a duplicate:

{
  kind: 'tortoise',
  hashtag: 'foo'

}

因为hashtag = foo已经被使用.

because hashtag=foo has already been taken.

问题是我只知道如何将$addToSet与简单的整数数组一起使用...

The problem is that I only know how to use $addToSet with simple arrays of integers...

例如,如果文章看起来像这样:

for example, if articles looked like this:

articles: [ 1 , 5 , 4, 2]

我将这样使用$ addToSet:

I would use $addToSet like this:

var data = {

    "$addToSet": {
     "articles": 9
   }

}

model.update(data);

但是我如何用唯一字段是字符串的对象数组(在这种情况下为'hashtag')完成同一件事?这些文档并不清楚,似乎我到处都在搜索.

but how can I accomplish the same thing with an array of objects where the unique field is a string, in this case 'hashtag'? The docs don't make this clear and it seems like I have searched everywhere..

谢谢

推荐答案

您需要使用 $ne 运算符.

You need to use the $ne operator.

var data = { 'kind': 'tortoise', 'hashtag': 'foo' };
Model.update(
    { 'articles.hashtag': { '$ne': 'foo' } }, 
    { '$addToSet': { 'article': data } }
)

仅当文章"数组中没有子文档的hashtag值等于"foo"时,这才会更新文档.

This will update the document only if there is no subdocument in the "article" array with the value of hashtag equals to "foo".

如评论中提到的@BlakesSeven

As @BlakesSeven mentioned in the comment

$addToSet 变得无关紧要值之一的存在,因此也可能是 $push 以确保代码清晰.但是该原理是正确的,因为 $addToSet 可以整体使用对象而不仅仅是对象的一部分.

The $addToSet becomes irrelevant once you are testing for the presence of one of the values, so this may as well be a $push for code clarity. But the principle is correct since $addToSet works on the whole object and not just part of it.

Model.update({ 
    { 'articles.hashtag': { '$ne': 'foo' } }, 
    { '$push': {'article':  data } }
)

这篇关于在对象数组上使用Mongoose/MongoDB $ addToSet功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆