【问题标题】:nodejs: How generate schema.pre('save',...) unique fieldnodejs:如何生成 schema.pre('save',...) 唯一字段
【发布时间】: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),因为它定义了模型的架构。

标签: node.js mongoose unique


【解决方案1】:

看起来您只是在生成 ident,但没有将其放入 MongoDB,并在将其保存之前尝试在其中找到它......

要能够访问具有该身份的文档,您需要先保存它。

尝试输入 console.log(err) 看看返回了什么错误

【讨论】:

  • 感谢您的回答。正如我所说,console.log('TWO'); 行无法访问。
  • 我尝试运行您的代码,它实际上进入了搜索回调函数内的“else”部分。也许它没有打印'TWO',因为它在if里面?因为 Node 是异步的,所以它是可能的。尝试仅将 console.log 放在“if”和“else”中。看看它打印了什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 2016-03-26
  • 2016-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多