gpt4 book ai didi

javascript - 查询MongoDB,用正则表达式替换一个特定字段

转载 作者:行者123 更新时间:2023-12-01 13:10:48 26 4
gpt4 key购买 nike

如果我有一个集合定义为,

const userSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
},

如何查询所有文档,但将每个密码替换为星号?

有点像,

const users = await User.find({
password: password.replace(/./gi, '*');
})

这可能吗?

最佳答案

您不能使用 find() 查询来执行此操作,因为它仅用于检索数据而不是可以使用 aggregate为此用 $addFields阶段。

const users = await User.aggregate([
{ "$addFields": {
"password": {
"$reduce": {
"input": { "$range": [0, { "$strLenCP": "$password" }] },
"initialValue": "",
"in": {
"$concat": [
"*",
"$$value"
]
}
}
}
}}
])

console.log({ users })

MongoPlayground

关于javascript - 查询MongoDB,用正则表达式替换一个特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60167111/

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