【发布时间】:2014-09-18 10:48:00
【问题描述】:
我在 mongoose 上有用户注册,我需要从可能的值中生成唯一的随机 ident 字段。问题是我无法查询到 mongodb。
控制台中脚本的结果是“ONE”。而已。 那么,错在哪里呢?有没有更好的方法来生成唯一的随机字段/数字?
schemaUser.pre('save', function (next) {
var self = this;
function genIdent() {
var ident = "", possible = "013456789";
for(var i=1; i <= 5; i++)
ident += possible.charAt(Math.floor(Math.random() * possible.length));
return ident;
}
function doIt() {
var ident = genIdent();
console.log('ONE');
mongoose.model('User', schemaUser).findOne({ident: ident}, function(err, o) {
console.log('TWO');
if (o) {
doIt();
} else {
self.ident = ident;
next();
}
});
}
doIt();
});
【问题讨论】:
-
您只能调用一次
mongoose.model('User', schemaUser),因为它定义了模型的架构。