mongoose - 如果不在数组中则添加,如果已在数组中则删除

时间:2013-03-17 20:19:18

标签: node.js mongodb mongoose

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

当然可以使用addToSet和remove(_id)来完成添加和删除。查询也没问题。我真的更关心用最短的方式做到这一点,而不费力。

例如,我建议采用架构:

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

假设引用数组包含元素:

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

案例1:我的方法收到5146014632B69A212E000002 (因此应删除此条目。)

案例2:我的方法收到5146014632B69A212E000004(因此应该添加此条目。)

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

这是逻辑,代码如下。

我通常使用underscore.js来完成这些任务,但你可以用JavaScript来完成。

  1. 获取文档。
  2. 遍历文档中的_ids,执行真值测试。
  3. 如果文档中包含您正在测试的_id,请从阵列中删除当前索引。
  4. 如果你已经浏览了整个数组,那里没有任何东西,array.push() _id。然后document.save()
  5. 这就是我通常遵循的方法。

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

    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' );
    

答案 2 :(得分:0)

@侯赛因答案,但使用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()
})()