私はユニークなユーザー名を持つユーザーモデルを作成しようとしています。ここではそのためのコードは次のとおりです。このMongooseのユニークな保存前検証で何が間違っていますか?
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String,
password: String,
});
UserSchema.virtual("password_confirmation").get(function() {
return this.pw_conf;
}).set(function(value) {
this.pw_conf = value;
});
UserSchema.path("username").required(true);
UserSchema.path("password").required(true);
UserSchema.pre("save",function(next, done) {
var self = this;
mongoose.models["User"].findOne({username : self.username},function(err, user) {
if(user) {
self.invalidate("user","username must be unique");
}
done();
});
next();
});
UserSchema.pre("save",function(next) {
if(this.pw_conf !== this.password) {
next(new Error("Must specify the password confirmation"));
}
else {
next();
}
});
module.exports = mongoose.model("User",UserSchema);
私も一意作品かどうかを確認するためにテストしていた。
var User = require("./users"),
mongoose = require("mongoose");
var u = new User();
mongoose.connect('mongodb://localhost/my_database');
u.username = "me";
u.password = "password";
u.password_confirmation = "password";
u.save(function(err) {
if(err) {
console.log(err);
}
mongoose.disconnect();
});
問題は、それがない、です。コードを実行するたびに、新しいオブジェクトが作成されます。一意性を保証する他の方法があるかもしれないことは承知していますが、私はこのようにしたいと思います。 findOne
メソッドの結果を処理した後、私はdone
に電話してはいけませんか?私はnext
と間違っていますか?
これはうまくいきましたが、エラー形式は同じではありません。したがって、APIを構築してエラーオブジェクト形式を数えれば、おそらくその方法に問題が生じます。私はhttps://npmjs.org/package/mongoose-unique-validatorをテストしました。それは私の魅力のように働いていました。エラーオブジェクトはほとんど同じです。 –
私の場合、これはうまくいきませんでした。関数のシグネチャを変更して(次の)引数を1つだけ変更し、次にパラメータを指定せずに次のエラーを呼び出す必要がありました。 – Matus
@Matus 'pre' [ミドルウェア](http://mongoosejs.com/docs/middleware.html):パラレル( 'next'と' done'パラメータ付き)、シリアル( 'next'だけ)。 – JohnnyHK