【问题标题】:Removing An Object From Core Mongoose Array Before Pushing New Object Into It在将新对象推入之前从核心 Mongoose 数组中删除对象
【发布时间】:2019-03-04 03:53:46
【问题描述】:

我有一个用户模型,其中有一组令牌。每个令牌都是一个具有三个键值对的对象。我只想在令牌数组中保留一个令牌对象,键为 '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”的所有现有对象,然后推送新对象,然后保存用户对象。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

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

    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 的对象。

    【讨论】:

    • 是mongo数组。正常的数组操作将不起作用。这个我已经试过了。
    猜你喜欢
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    相关资源
    最近更新 更多