在使用保存功能之前,我尝试检查 token 是否唯一,因为我无法从内部创建 token 。
我尝试过使用 count、find 和 findOne 函数,但没有成功...
exports.create_client = function(req, res){
token = crypto.randomBytes(8).toString('hex') + '-' + crypto.randomBytes(8).toString('hex') + '-' + crypto.randomBytes(8).toString('hex')
var client = new Client({
first_name: req.body.first_name,
last_name: req.body.last_name,
phone_number: req.body.phone_number,
pin_code: pincode_generator(6),
token: token
});
client.save(function(err, userClient){
if (err){
if(err.errors.phone_number)
res.status(400).send('Phone number is in use.');
if(err.errors.token)
res.status(400).send('Token is in use.');
} else {
res.status(201).send('User created successfully!')
}
});
};
由于 token 是在服务器端创建的,因此服务器有责任提供唯一的 token 并防止错误。
最佳答案
将数据保存到 Mongodb 之前
你应该在用 Mongoose 定义你的架构时
将 unique: true
设置为您想要保存为唯一的字段
var clientSchema = new Schema({
first_name: String,
last_name: String,
phone_number: {type: String , unique : true }
pin_code: String,
token: {type: String , unique : true }
});
你应该处理错误
关于javascript - 如何检查 Mongoose 中是否存在值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57056953/