Node.js - mongoose 静态方法示例

3
我希望能在模型UserModel上定义一个方法,这个方法可以获取所有userId小于10的用户的姓名。
以下是我的实现:
// 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似乎不起作用。但如果是这种情况,那么有什么方法可以解决呢?这个异步的东西有点让人感到压抑。

2个回答

9
添加回调函数,并将用户作为以下形式返回:
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(..., ...) - p0lAris
看起来find方法是异步的,所以你想要的是不可能的。你可以对users做任何你想做的事情(不仅仅是console.log),但只能在异步回调中执行。你可以发布你代码的其余部分,并寻求帮助来整合getUsersWithIdLessThan10,但实际上你不能做太多关于异步方法的事情... - Alex Netkachov
如果我创建一个 API 只返回这些用户名的列表,我该怎么做呢?就是这么简单。 - p0lAris
3
这是使用 Node 工作的乐趣。它使用 JavaScript,一切都是异步的,并在一个线程中运行,因此非常快速且令人喜欢。但几周后,您会明白什么是“回调地狱”。 - Alex Netkachov

1
尝试这个:

API 代码:

var UserApi = require('./UserSchema');

var callback = function(response){
    console.log(response); // or res.send(200,response);
}

UserApi.getUsersWithIdLessThan10(callback);

UserSchema 代码:

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);
          })
        }
    })
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接