在将新对象推入核心猫鼬阵列之前,从核心猫鼬阵列中删除对象

时间:2018-09-28 07:28:39

标签: node.js mongoose

我有一个用户模型,其中有一组令牌。每个令牌是具有三个键值对的对象。我只想用键'access'='auth'在令牌数组中保留一个令牌对象。我编写的代码无法正常工作。每次我运行该代码时,都会推送新令牌而不删除它键为'access'='auth'的现有对象。请提供帮助。

我的用户对象如下:-

 {
        "_id": "5badcc621818710a2a8fcafa",
        "email": "example@gmail.com",
        "password": "example",
        "tokens": [
            {
                "_id": "5badcc661818710a2a8fcafb",
                "access": "auth",
                "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
            },
            {
                "_id": "5badcf6b11a6610a9d5b3f52",
                "access": "auth",
                "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
            },
            {
                "_id": "5badcf853776410aa7bdfaba",
                "access": "auth",
                "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
            }
        ]
    }

此函数被调用时,我正在将新对象推入令牌数组:-

userSchema.methods.genAuthToken = function () {

    var token = jwt.sign(data, SECRET_KEY).toString();

    var access = 'auth';
  

===> this.tokens.pull({access:'auth'}); //不工作

    this.tokens.push({ access, token });

    return this.save().then(() => token);
}

我想删除键“ access”的值为“ auth”的所有现有对象,然后推送新对象,然后保存用户对象。

1 个答案:

答案 0 :(得分:0)

改为使用过滤器。下面的代码应该可以工作:

userSchema.methods.genAuthToken = function(){

var token = jwt.sign(data, SECRET_KEY).toString();

var access = 'auth';
  

this.tokens = this.tokens.filter(function(token){return token.access!=='auth'});

this.tokens.push({ access, token });

return this.save().then(() => token);

过滤器将删除所有具有与auth相同访问权限的对象。

相关问题