如何在以mongoose保存编辑数据之前进行验证?
例如,如果数据库中已存在sample.name
,则用户将收到某种错误,类似于此,这是我的代码
//Post: /sample/edit
app.post(uri + '/edit', function (req, res, next) {
Sample.findById(req.param('sid'), function (err, sample) {
if (err) {
return next(new Error(err));
}
if (!sample) {
return next(new Error('Invalid reference to sample information'));
}
// basic info
sample.name = req.body.supplier.name;
sample.tin = req.body.supplier.tin;
// contact info
sample.contact.email = req.body.supplier.contact.email;
sample.contact.mobile = req.body.supplier.contact.mobile;
sample.contact.landline = req.body.supplier.contact.landline;
sample.contact.fax = req.body.supplier.contact.fax;
// address info
sample.address.street = req.body.supplier.address.street;
sample.address.city = req.body.supplier.address.city;
sample.address.state = req.body.supplier.address.state;
sample.address.country = req.body.supplier.address.country;
sample.address.zip = req.body.supplier.address.zip;
sample.save(function (err) {
if (err) {
return next(new Error(err));
}
res.redirect(uri + '/view/' + sample._id);
});
});
});
答案 0 :(得分:54)
通常你可以使用mongoose validation但是因为你需要一个异步结果(现有名称的db查询)和验证器不支持promises(从我能说的),你需要创建自己的函数和传递一个回调。这是一个例子:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
mongoose.connect('mongodb://localhost/testDB');
var UserSchema = new Schema({
name: {type:String}
});
var UserModel = mongoose.model('UserModel',UserSchema);
function updateUser(user,cb){
UserModel.find({name : user.name}, function (err, docs) {
if (docs.length){
cb('Name exists already',null);
}else{
user.save(function(err){
cb(err,user);
});
}
});
}
UserModel.findById(req.param('sid'),function(err,existingUser){
if (!err && existingUser){
existingUser.name = 'Kevin';
updateUser(existingUser,function(err2,user){
if (err2 || !user){
console.log('error updated user: ',err2);
}else{
console.log('user updated: ',user);
}
});
}
});
更新:更好的方法
预钩似乎是一个更自然的停止保存的地方:
UserSchema.pre('save', function (next) {
var self = this;
UserModel.find({name : self.name}, function (err, docs) {
if (!docs.length){
next();
}else{
console.log('user exists: ',self.name);
next(new Error("User exists!"));
}
});
}) ;
更新2:异步自定义验证器
看起来mongoose现在支持异步自定义验证器,所以这可能是自然的解决方案:
var userSchema = new Schema({
name: {
type: String,
validate: {
validator: function(v, cb) {
User.find({name: v}, function(err,docs){
cb(docs.length == 0);
});
},
message: 'User already exists!'
}
}
});
答案 1 :(得分:7)
继续使用示例@nfreeze的另一种方法是使用此验证方法:
UserModel.schema.path('name').validate(function (value, res) {
UserModel.findOne({name: value}, 'id', function(err, user) {
if (err) return res(err);
if (user) return res(false);
res(true);
});
}, 'already exists');
答案 2 :(得分:2)
这是用更少的代码完成此任务的另一种方法。
更新3:异步模型类静态
与选项2类似,这允许您创建直接链接到模式的函数,但使用模型从同一文件调用。
<强> model.js 强>
userSchema.statics.updateUser = function(user, cb) {
UserModel.find({name : user.name}).exec(function(err, docs) {
if (docs.length){
cb('Name exists already', null);
} else {
user.save(function(err) {
cb(err,user);
}
}
});
}
从文件调用
var User = require('./path/to/model');
User.updateUser(user.name, function(err, user) {
if(err) {
var error = new Error('Already exists!');
error.status = 401;
return next(error);
}
});
答案 3 :(得分:1)
如果您正在使用唯一索引进行搜索,那么使用UserModel.count实际上可能比UserModel.findOne更好,因为它返回整个文档(即执行读取)而不是只返回一个int。
答案 4 :(得分:1)
除了已经发布的示例之外,还有另一种使用 express-async-wrap 和异步函数(ES2017)的方法。
<强>路由器强>
router.put('/:id/settings/profile', wrap(async function (request, response, next) {
const username = request.body.username
const email = request.body.email
const userWithEmail = await userService.findUserByEmail(email)
if (userWithEmail) {
return response.status(409).send({message: 'Email is already taken.'})
}
const userWithUsername = await userService.findUserByUsername(username)
if (userWithUsername) {
return response.status(409).send({message: 'Username is already taken.'})
}
const user = await userService.updateProfileSettings(userId, username, email)
return response.status(200).json({user: user})
}))
<强> UserService 强>
async function updateProfileSettings (userId, username, email) {
try {
return User.findOneAndUpdate({'_id': userId}, {
$set: {
'username': username,
'auth.email': email
}
}, {new: true})
} catch (error) {
throw new Error(`Unable to update user with id "${userId}".`)
}
}
async function findUserByEmail (email) {
try {
return User.findOne({'auth.email': email.toLowerCase()})
} catch (error) {
throw new Error(`Unable to connect to the database.`)
}
}
async function findUserByUsername (username) {
try {
return User.findOne({'username': username})
} catch (error) {
throw new Error(`Unable to connect to the database.`)
}
}
// other methods
export default {
updateProfileSettings,
findUserByEmail,
findUserByUsername,
}
<强>资源强>
答案 5 :(得分:1)
对于任何使用此旧解决方案的人。有一个更好的方法 from the mongoose docs。
var s = new Schema({ name: { type: String, unique: true }});
s.path('name').index({ unique: true });
答案 6 :(得分:1)
通过一个查询检查数据库中是否已存在电子邮件或电话号码
let userDB = await UserS.findOne({ $or: [
{ email: payload.email },
{ phoneNumber: payload.phoneNumber }
] })
if (userDB) {
if (payload.email == userDB.email) {
throw new BadRequest({ message: 'E-mail already exists' })
} else if (payload.phoneNumber == userDB.phoneNumber) {
throw new BadRequest({ message: 'phoneNumber already exists' })
}
}
答案 7 :(得分:0)
使用the mongoose exists function
是更简单的方法router.post("/groups/members", async (ctx) => {
const group_name = ctx.request.body.group_membership.group_name;
const member_name = ctx.request.body.group_membership.group_members;
const GroupMembership = GroupModels.GroupsMembers;
console.log("group_name : ", group_name, "member : ", member_name);
try {
if (
(await GroupMembership.exists({
"group_membership.group_name": group_name,
})) === false
) {
console.log("new function");
const newGroupMembership = await GroupMembership.insertMany({
group_membership: [
{ group_name: group_name, group_members: [member_name] },
],
});
await newGroupMembership.save();
} else {
const UpdateGroupMembership = await GroupMembership.updateOne(
{ "group_membership.group_name": group_name },
{ $push: { "group_membership.$.group_members": member_name } },
);
console.log("update function");
await UpdateGroupMembership.save();
}
ctx.response.status = 201;
ctx.response.message = "A member added to group successfully";
} catch (error) {
ctx.body = {
message: "Some validations failed for Group Member Creation",
error: error.message,
};
console.log(error);
ctx.throw(400, error);
}
});