【问题标题】:Node.js — mongoose static method exampleNode.js — mongoose 静态方法示例
【发布时间】:2013-11-12 06:10:27
【问题描述】:

我希望在模型UserModel 上定义一个方法,以便我获得所有用户 ID

以下是我的实现:

// pseudo code
UserModel === {
    userId : Number,
    userName: String
}

UserSchema.statics.getUsersWithIdLessThan10 = function(){
    var usersLessThan10 = []
    this.find({userId : {$lt : 10}}, function(error, users){
        users.forEach(function(user){
            console.log(user.userName) // ... works fine
            usersLessThan10.push(user.userName)
        })
    })
    return usersLessThan10
}

我明白为什么这似乎不起作用 - 异步查找 API。但如果是这样的话,那该怎么做呢?这种异步的东西有点压倒性。

【问题讨论】:

    标签: node.js mongodb asynchronous mongoose


    【解决方案1】:

    添加回调并在此回调中返回用户如下:

    UserSchema.statics.getUsersWithIdLessThan10 = function(err, callback) {
        var usersLessThan10 = []
        this.find({userId : {$lt : 10}}, function(error, users){
            users.forEach(function(user){
                console.log(user.userName) // ... works fine
                usersLessThan10.push(user.userName)
            })
            callback(error, usersLessThan10)
        })
    }
    

    然后用回调调用usersLessThan10

    ... .usersLessThan10(function (err, users) {
        if (err) {
            // handle error
            return;
        }
        console.log(users);
    })
    

    【讨论】:

    • 我不需要记录它们。我只需要一份清单。我需要类似:var users = getUsersWithIdLessThan10(..., ...)
    • 看来find 方法是异步的,所以你所问的只是它不可能。你可以用users(不仅仅是console.log)做任何你想做的事情,但只能在异步回调中。您可以发布其余代码并寻求有关如何合并 getUsersWithIdLessThan10 的帮助,但使用异步方法确实不能做太多...
    • 如果我创建一个 API 来只返回这些用户名的列表,我会怎么做?就这么简单。
    • 这是使用节点的乐趣。它是 JavaScript,一切都是异步的,并且在一个线程中工作,因此速度非常快,您喜欢它,但几周后您就会明白“回调地狱”的含义。
    【解决方案2】:

    试试这个:

    API 代码:

    var UserApi = require('./UserSchema');
    
    var callback = function(response){
        console.log(response); // or res.send(200,response);
    }
    
    UserApi.getUsersWithIdLessThan10(callback);
    

    用户架构代码:

    UserSchema.getUsersWithIdLessThan10 = function(callback){
        var usersLessThan10 = []
        this.find({userId : {$lt : 10}}, function(error, users){
            if (error)
               { callback(error)}
            else{
              users.forEach(function(user){
                  console.log(user.userName) // ... works fine
                  usersLessThan10.push(user.userName);
                  //TODO: check here if it's the last iteration
                     callback(usersLessThan10);
              })
            }
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-22
      • 2012-11-12
      • 2015-01-22
      • 2013-06-06
      • 2017-01-06
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多