【发布时间】: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”的所有现有对象,然后推送新对象,然后保存用户对象。
【问题讨论】: