gpt4 book ai didi

node.js - 在 Mongoose 查询中选择字段值不等于某些内容的字段

转载 作者:太空宇宙 更新时间:2023-11-03 22:05:03 25 4
gpt4 key购买 nike

我基本上是在尝试更新文档,然后从结果中选择字段值不等于某些值的字段。假设 jwt_idb816cf00e9f649fbaf613e2ca2d523b5

查询

const removeDevices = await Identity.findOneAndUpdate(
{
userID: user_id
},
{
$pull: {
activeTokens: {
jti: {
$ne: jwt_id
}
}
}
},
).select(["-_id", "activeTokens.jti"]);

现在,运行此查询会产生以下输出:

{ activeTokens:
[ { jti: '5d872359af2c47e5970c1fae531adf0e' },
{ jti: 'd3ac84f520614067b1caad504d7ab27f' },
{ jti: '25c6fa96705c4eec96e1427678c3ff50' },
{ jti: 'b816cf00e9f649fbaf613e2ca2d523b5' }
]
}

如何从 select 命令中获取除 { jti: b816cf00e9f649fbaf613e2ca2d523b5 } 之外的所有 jti 字段?

所需输出

{ activeTokens:
[ { jti: '5d872359af2c47e5970c1fae531adf0e' },
{ jti: 'd3ac84f520614067b1caad504d7ab27f' },
{ jti: '25c6fa96705c4eec96e1427678c3ff50' },
]
}

最佳答案

未经测试很难确定,但我不认为 mongoose 在修改后返回文档,而是简单地返回匹配的文档。因此,我认为在 findOneAndUpdate 的情况下,您必须让查询匹配才能进行拉取,然后在应用程序代码中再次手动过滤数组以获得所需的输出。

这可能有效:

const removeDevices = await Identity.findOneAndUpdate(
{
userID: user_id
},
{
$pull: {
'activeTokens.jti': { $ne: jwt_id }
}
},
).select(["-_id", "activeTokens.jti"]).then(identity=>identity.activeTokens.filter(token=>token.jti!==jwt_id));

如果上述方法由于某种原因不起作用,那么我会尝试更简单的方法

简单:

const removeDevices = await Identity.findOne({userID: user_id}).select(["-_id", "activeTokens"]).then(identity=>{
const removedTokens = []
identity.activeTokens = identity.activeTokens.filter(token=>{
if(token.jti===jwt_id) {
return true;
}
removedTokens.push(token);
})
identity.save(err=>{
console.log('doc saved')
});
return removedTokens;
});

或(原子):

const removeDevices = await Identity.findOne({userID: user_id}).select('activeTokens','jti _id').then(identity=>{
const removedTokens = identity.activeTokens.filter(token=>token.jti!==jwt_id);
const result = await Identity.update({userId:user_id},{$pull:{'activeTokens._id': { $in: removedTokens.map(t=>t._id) } }});
console.log(result.nModified);
return removedTokens;
});

关于node.js - 在 Mongoose 查询中选择字段值不等于某些内容的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56417300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com