gpt4 book ai didi

javascript - 即使给出了必填字段,也会发生 mongoose 验证错误

转载 作者:行者123 更新时间:2023-11-30 19:37:09 27 4
gpt4 key购买 nike

    // Assign unique krypter id
assignKrypterID = () =>
{
let id = Math.floor(Math.random()*(999999-100000)+100000);
console.log(id);
Krypter
.findOne({krypter_id: id.toString()})
.then(krypter => {
if (krypter)
assignKrypterID()
else
return id.toString()
})
.catch(err => console.log(err))
}

const newKrypter = new Krypter({
handle: req.body.handle,
password: req.body.password, // plain text
krypter_id: assignKrypterID()
});

// Hashes the plaintext password and saves it
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newKrypter.password, salt, (err, hash) => {
if (err) throw err;
newKrypter.password = hash; // encrypted password
newKrypter
.save()
.then(krypter => res.json(krypter))
.catch(err => console.log(err));
})
});

我尝试在注册期间使用函数“assignKrypterID()”为每个用户分配一个唯一的 6 位数字 ID。但是得到如下错误:

Obtained error

这是我的模式:

const KrypterSchema = new Schema({
handle: {
type: String,
required: true
},
password: {
type: String,
required: true
},
krypter_id: {
type: String,
required: true
}
});

这不能用递归来实现吗?还是递归在这里是一个糟糕的举动?

帮助我如何修改它以查找随机生成的 Id 是否已分配给对象。

最佳答案

assignKrypterID = async() => {
try {
let krypter_ids = await Krypter.find({}).map(obj => obj.krypter_id)
let flag = true
while (flag) {
let id = Math.floor(Math.random() * (999999 - 100000) + 100000);
console.log(id);
if (krypter_ids.includes(id)) {
continue;
} else {
flag = false
return id.toString()
}
}
} catch (err) {
throw err
console.log(err)
}
}
async function foo() {
try {
let krypter_id = (await assignKrypterID()) || ""
const newKrypter = new Krypter({
handle: req.body.handle,
password: req.body.password, // plain text
krypter_id: krypter_id
});

// Hashes the plaintext password and saves it
let salt = await bcrypt.genSalt(10)
let hash = await bcrypt.hash(newKrypter.password, salt)
newKrypter.password = hash; // encrypted password
let krypter = await newKrypter.save()
res.json(krypter)
} catch (err) {
console.log(err)
throw err
}

}

foo()

关于javascript - 即使给出了必填字段,也会发生 mongoose 验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55815464/

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