【问题标题】:mongoose - Add if not in array, remove if already in array猫鼬 - 如果不在数组中则添加,如果已经在数组中则删除
【发布时间】:2020-04-15 12:53:24
【问题描述】:

在 mongoose 中确定元素是否已经在数组中的最快方法是什么。在这种情况下,我想从该数组中删除元素。如果数组不包含我要添加的特定元素。

当然,添加和删除可以使用 addToSet 和 remove(_id) 来完成。查询也没有问题。我真的更关心用最短的方法来做这件事,用更少的努力。

例如我建议采用 Schema:

var StackSchema = new Schema({
    references: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});

假设引用数组包含元素:

['5146014632B69A212E000001',
 '5146014632B69A212E000002',
 '5146014632B69A212E000003']

案例1:我的方法收到5146014632B69A212E000002 (所以这个条目应该被删除。)

案例2:我的方法接收到5146014632B69A212E000004(所以应该加上这个条目。)

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    任何路过的人的解决方案。 :)

    if(doc.references.indexOf(SOMESTRING) !== -1) {
        console.log('it\'s there') ; doc.likes.pull(SOMESTRING);
    }else{
        doc.references.push(SOMESTRING);
    }
    

    【讨论】:

      【解决方案2】:

      逻辑如下,代码如下。

      我通常将 underscore.js 用于此类任务,但您可以仅使用 JavaScript 来完成。

      1. 获取文档。
      2. 遍历文档中的 _id,执行真值测试。
      3. 如果文档具有您正在测试的 _id,请从数组中删除当前索引。
      4. 如果您浏览了整个数组并且其中没有任何内容,请array.push() _id。然后document.save()

      这是我通常遵循的方法。

      在下划线中,它会是这样的:

      function matching(a,b) { // a should be your _id, and b the array/document
        var i;
        for ( i = 0, i < b.length , i++) {
          if ( a.toString() === b[i].toString() )
            return i;
          else return -1;
        }
      };
      

      然后你会这样使用这个函数:

      var index = matching( '5146014632B69A212E000002', doc );
      if ( index > -1 )
        doc.splice( index , 1);
      else 
        doc.push( '5146014632B69A212E000002' );
      

      【讨论】:

        【解决方案3】:

        @Hussein 回答,但使用 Lodash:

        const _ = require("lodash")
        
        const User = require("./model")
        
        const movies = ["Inception", "Matrix"]
        
        (async () => {
            // Catch errors here
            const user = User.findById("")
        
            const userMoviesToggle = _.xor(
                user.movies, // ["Inception"]
                movies
            ); // ["Matrix"]
        
            user.movies = userMoviesToggle
        
            // Catch errors here
            user.save()
        })()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-10-14
          • 1970-01-01
          • 1970-01-01
          • 2015-02-09
          • 1970-01-01
          • 2020-04-28
          • 1970-01-01
          相关资源
          最近更新 更多