$或使用Mongoose搜索

rem*_*ion 4 mongoose mongodb node.js

我试图找出用户是否输入了重复的名称和/或电子邮件地址.我是Mongoose的新手(也就MongoDb而言),但根据我所读的内容,这似乎是正确的.然而,它返回真实 - 无论如何.如果我单独找到一个,而不是$或者,它似乎工作正常.

// check if user exists
var userExists = function(u, callback) {
  User.find({$or:[ {'username': u.username}, {'email': u.email}]} , function(err,user) {
    if (err) {      // err, so not sure if user exists
        callback(1);
        return;
        } 
    if (user) { // user, so return exists
        callback(1);
        return;
        } 
    //no error, no user
    callback(0);
    });
};
Run Code Online (Sandbox Code Playgroud)

想法?

rem*_*ion 6

更新的方法来检查user.length它是否为null.如果Mongoose(或MongoDB)找不到该文档,则它不会返回null.

// check if user exists
var userExists = function(u, callback) {
  User.find({$or:[ {'username': u.username}, {'email': u.email}]} , function(err,user) {
    if (err || user.length > 0) {     // user does not come back null, so check length
        callback(1);
        return;
    } 
    //no error, no user
    callback(0);
  });
};
Run Code Online (Sandbox Code Playgroud)

  • @Ajaybeni他正在使用Mongoose所以`user`是一个数组而不是一个游标. (3认同)