试图在for循环中使用FindOne mongoose方法

时间:2014-12-29 09:50:36

标签: node.js mongodb meanjs

我正在尝试使用我的用户模型的mongoose findOne方法来查找displayName(如果它已经存在),如果我想更改显示名称并再次检查其唯一性,直到找不到唯一的displayname。我写的代码是这样的:

   var mongoose = require('mongoose'),
    User = mongoose.model('User'),
exports.signup = function(req, res) {
delete req.body.roles;
var message = null;
// Add missing user fields
req.body.provider='local';
req.body.displayName = req.body.firstName + ' ' + req.body.lastName;

var flag=false;
for( var i=1;i>=1;i++) {
    console.log(req.body.displayName);
    if(!flag) {
        User.findOne({'displayName': req.body.displayName}, function (err, user) {
            if (user) {
                req.body.displayName = req.body.firstName + ' ' + req.body.lastName + '.' + i;
            }
            if (err) {
                flag = true;
            }
        });
    }
    else break;
}
var user = new User(req.body);
// Then save the user 
user.save(function(err) {
    if (err) {
        console.log('failed to save user');
        });
    } else {
        // Remove sensitive data before login
        user.password = undefined;
        user.salt = undefined;
    }
 });

上面的代码提示错误:

                });
                  ^ Don't make functions within a loop.

我应该如何使用此代码生成唯一的显示名称?

非常感谢您提供的任何帮助!

-Parv

1 个答案:

答案 0 :(得分:0)

您需要将用户保存在find by username功能的回调中:

req.body.provider='local';
req.body.displayName = req.body.firstName + ' ' + req.body.lastName;

User.findOne({'displayName': req.body.displayName}, function (err, user) {
    if (err) {
      flag = true;
    }
    if (user) {
        req.body.displayName = req.body.firstName + ' ' + req.body.lastName + '.' + i;
        return res.render('view');
    }

    user.save(function(err) {
       if (err) {
           console.log('failed to save user');
       } else {
           // Remove sensitive data before login
           user.password = undefined;
           user.salt = undefined;
       }
    });
});

此外,您在此处有语法错误:

    if (err) {
         console.log('failed to save user');
    }); //this line should be replaced with a single closing bracket