首页 \ 问答 \ 使用Node.js在MongoDB操作中回调(Callback at MongoDB Operation With Node.js)

使用Node.js在MongoDB操作中回调(Callback at MongoDB Operation With Node.js)

出于组织目的,我将源代码分离为模块,例如我在node.js应用程序上有user模块,该应用程序负责从MongoDB数据库中检索用户信息。 我正在做这样的事情:

var mongo = require("mongodb"),
    Server = mongo.Server,
    Db = mongo.Db;

var server = new Server("localhost", 27017, { auto_reconnect: true });
var db = new Db("users", server);

module.exports = {
    login: function(user, pass, callback) {
        var reg_result = null;

        db.open(function (err, db) {
            if(!err) {
                db.collection("users", function(err, collection) {
                    collection.findOne(
                        {
                            "username": user,
                            "password": pass
                        },
                        function(err, item) {
                            if(!err) {
                                reg_result = item;
                            } else {
                                reg_result = "error";
                            }
                        }
                    );
                });
            } else {
                reg_result = "error";
                console.log("ERROR: " + err);
            }
        });

        callback(reg_result);
    }
}

并在我的测试脚本上执行它,如下所示:

var user = require("./user.js");

user.log("test", "test", function(msg) {
    console.log(msg);
});

它执行数据库操作并检索值,但每次只返回null ,当我不初始化reg_result变量时,它返回undefined 。 我该怎么做才能纠正这个问题?

我在user.js上使用console.log调试并输出了user.js ,但是我想要回调,所以我可以在其他源上使用该项,比如我的测试脚本


For organization purposes I'm separating my source code into modules, for example I have the user module on my node.js app which is responsable for retrieving user information from a MongoDB database. I'm doing something like this:

var mongo = require("mongodb"),
    Server = mongo.Server,
    Db = mongo.Db;

var server = new Server("localhost", 27017, { auto_reconnect: true });
var db = new Db("users", server);

module.exports = {
    login: function(user, pass, callback) {
        var reg_result = null;

        db.open(function (err, db) {
            if(!err) {
                db.collection("users", function(err, collection) {
                    collection.findOne(
                        {
                            "username": user,
                            "password": pass
                        },
                        function(err, item) {
                            if(!err) {
                                reg_result = item;
                            } else {
                                reg_result = "error";
                            }
                        }
                    );
                });
            } else {
                reg_result = "error";
                console.log("ERROR: " + err);
            }
        });

        callback(reg_result);
    }
}

And executing it on my test script like this:

var user = require("./user.js");

user.log("test", "test", function(msg) {
    console.log(msg);
});

It does the database operation and retrieves the value, but every time it only returns null, when I don't initialize the reg_result variable it returns undefined. What should I do to correct this?

I debugged using console.log on the user.js and the item was outputted, but I want to have the callback so I can use the item on other sources, like my test script


原文:https://stackoverflow.com/questions/9743564
更新时间:2022-05-27 21:05

最满意答案

出于一个简单的原因,您不会找到关于ToArray方法可能异常的文档。 这是一个有很多“重载”的扩展方法。 它们都有相同的方法签名,但对于不同的集合类型,实现是不同的,例如List<T>HashSet<T>

但是,我们可以对大多数.NET Framework BCL因性能原因不执行任何锁定的代码进行安全假设。 我还特别检查了List<T>ToList实现。

public T[] ToArray()
{
    T[] array = new T[this._size];
    Array.Copy(this._items, 0, array, 0, this._size);
    return array;
}

正如您可能已经想象的那样,这是非常简单的代码,最终在mscorlib执行。 对于此特定实现,您还可以在MSDN页面中查看Array.Copy方法中可能出现的异常。 它归结为一个异常,如果在刚分配目标数组之后列表的排名发生变化,则抛出异常。

考虑到List<T>是一个简单的例子,你可以想象出在需要更复杂的代码以存储在数组中的结构上出现异常的机会。 Queue<T>是一个更可能失败的候选人:

public T[] ToArray()
{
    T[] array = new T[this._size];
    if (this._size == 0)
    {
        return array;
    }
    if (this._head < this._tail)
    {
        Array.Copy(this._array, this._head, array, 0, this._size);
    }
    else
    {
        Array.Copy(this._array, this._head, array, 0, this._array.Length - this._head);
        Array.Copy(this._array, 0, array, this._array.Length - this._head, this._tail);
    }
    return array;
}

You will not find documentation about possible exceptions of ToArray method for one simple reason. This is an extension method that has many 'overloads'. They all have same method signature, but implementation is different for different collection types, e.g. List<T> and HashSet<T>.

However, we can make a safe assumption for most of the code that .NET framework BCL does not perform any locking for performance reasons. I've also checked very specifically implementation of ToList for List<T>.

public T[] ToArray()
{
    T[] array = new T[this._size];
    Array.Copy(this._items, 0, array, 0, this._size);
    return array;
}

As you might have imagined, it's quite simple code which ends up executing in mscorlib. For this specific implementation, you can also see exceptions which could occur in MSDN page for Array.Copy method. It boils down to an exception which is thrown if rank of the list changes right after destination array was just allocated.

Having in mind that List<T> is trivial example, you can imagine that chances for exception rise on structures which require more complicated code in order to store in an array. Implementation for Queue<T> is a candidate which is more likely to fail:

public T[] ToArray()
{
    T[] array = new T[this._size];
    if (this._size == 0)
    {
        return array;
    }
    if (this._head < this._tail)
    {
        Array.Copy(this._array, this._head, array, 0, this._size);
    }
    else
    {
        Array.Copy(this._array, this._head, array, 0, this._array.Length - this._head);
        Array.Copy(this._array, 0, array, this._array.Length - this._head, this._tail);
    }
    return array;
}

相关问答

更多
  • 这是因为Enumerable.ToArray与并发集合一起使用并不安全。 你应该声明你的内部变量的类型是ConcurrentDictionary而不是IDictionary ,因为这会使用由字典本身实现的ToArray实现,而不是依赖于扩展方法: private readonly IDictionary _cache = new ConcurrentDictionary(); 特别是, Enumerable.ToArray在内部使用B ...
  • 出于一个简单的原因,您不会找到关于ToArray方法可能异常的文档。 这是一个有很多“重载”的扩展方法。 它们都有相同的方法签名,但对于不同的集合类型,实现是不同的,例如List和HashSet 。 但是,我们可以对大多数.NET Framework BCL因性能原因不执行任何锁定的代码进行安全假设。 我还特别检查了List的ToList实现。 public T[] ToArray() { T[] array = new T[this._size]; Array.Copy( ...
  • count()仍然可以使用toArray()来删除: properties.find(searchParams).toArray(function (err, result) { var i, count; for (i = 0, count = result.length; i < count; i++) { propArray.push(new models.propertyModel(result[i])); } db.close(); ...
  • 你没有抛出一个std::string ,而是一个nul终止的字符串( "ERROR" is really const char[6]的类型"ERROR" is really const char[6] ,而throw表达式将其衰减为const char* 。)。 所以你没有抓住异常。 如果你改变throwE来抛出一个std::string ,它会按预期工作: void throwE(){ throw std::string("ERROR"); } 或者,捕获一个const char* ,它与const ...
  • 没有UnderflowException 。 如果你这样做: var stack = new Stack(); stack.Push(1); var x1 = stack.Pop(); var x2 = stack.Pop(); 你将得到InvalidOperationException : 堆空。 但是你完全可以自由地创建你自己的Exception类: public class UnderflowException : Exception { public UnderflowException( ...
  • 类名是Product ,而不是product 。 案件很重要。 The class name is Product, not product. Case matters.
  • 我认为没有什么不清楚 - 就像你所描述的那样。 如果异常类的.what()方法抛出一个错误,那么整个catch工作就会被浪费 : try { someDangerousOperation(); } catch(std::exception e) { // Ooops, instead of false, //we get another exception totally unrelated to original error someLogClassOrWhatever.save(e.wh ...
  • 我认为这是你遇到的问题。 如果你需要高性能,我会看看SocketAsyncEventArgs 。 此外,提升事件将阻止您的线程,直到事件完成。 我会有两个线程,一个从套接字读取并将数据放入队列。 另一个从队列中读取数据并对其进行处理。 I think this is the least of your problem. If you need high-performance I would look at SocketAsyncEventArgs. Also, raising the event will ...
  • MongoDB承认这种行为,但他们也说这是按设计工作的。 它已被记录为MongoDB JIRA中的错误, $ out聚合阶段不生效 ,并且响应表明它不是错误: 此行为是故意的,并且在一段时间内没有使用节点驱动程序进行更改。 当您通过调用Collection.prototype.aggregate“运行”聚合时,我们创建一个中间Cursor,直到请求某种I / O才会执行。 这允许我们提供可链接的游标API(例如cursor.limit(..)。sort(..)。project(..)),在执行初始查询之前在 ...
  • throw是一个语句,因此不能在需要表达式的地方使用它。 您可以创建一个只抛出错误的函数,然后将该函数作为表达式的一部分调用: function throwMissing ( ) { throw new Error( 'missing' ); } 当你想抛出错误时: var x = lookupSomeValue() || throwMissing(); 当然你也可以使用匿名函数: var x = lookupSomeValue() || function(){ throw new Error ...

相关文章

更多

最新问答

更多
  • 使用通配符获取更多servlet请求变量[重复](Get more servlet request variables using wildcards [duplicate])
  • 返回相同的集合类型,参数化不同(Returning same collection type, differently parameterised)
  • C ++朋友函数模板重载和SFINAE在clang ++,g ++,vc ++中的不同行为(C ++ 14模式)(C++ friend function template overloading and SFINAE different behaviors in clang++, g++, vc++ (C++14 mode))
  • 与paure IoT-Hub的Python paho-MQTT连接(Python paho-MQTT connection with azure IoT-Hub)
  • 编译器警告“来自不同的Objective-C类型的赋值”(Compiler warning “assignment from distinct objective-c type”)
  • C ++编译错误(在此函数中未初始化)[重复](C++ Compile Error (uninitialized in this function) [duplicate])
  • unsigned-signed下溢机制(unsigned-signed underflow mechanism)
  • 快速行查询的数据结构?(Data structure for fast line queries?)
  • 饥荒有手机安卓版的吗
  • Jquery可拖动碰撞检测错误(Jquery draggable collision detection bug)
  • sql调优是怎样来实现的?
  • 无法使占位符输入文本消失(Unable to make the placeholder input text disappear)
  • jQuery改变了两个div的CSS属性(JQuery change CSS property of two div's)
  • JDK中包含的库版本(Versions of libraries included in the JDK)
  • 请问下载的是出现ASP是什么意思
  • Firebase MLkit用于数字液晶显示器的文本识别(Firebase MLkit Text recognition for digital lcd displays)
  • 我可以在任何平台上运行C和C ++吗?(Can I run C and C++ on any platform?)
  • 让小组在C#的特定位置(get panel at specific positions in C#)
  • Nagios为通知设置了更高的间隔(Nagios set higher interval for notifications)
  • 无法向SMTP主机发送电子邮件(unable to send an email to SMTP host)
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何在.NET代码中验证全球邮政编码(How can I validate worldwide postal codes in my .NET code)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • Clojure:减少大型懒惰收集会占用内存(Clojure: Reducing large lazy collection eats up memory)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • 显示作为字符串的SVG(Showing an SVG that I have as a string)
  • 从jansson库里创建json请求的自由内存的正确方式是什么?(what is the proper way of free memory in creating json request from jansson libary?)
  • jQuery插件无法正常工作 - 它是附加的(jQuery plugin not working - it's appended)
  • 使用stat_summary自动调整ylim(Automatically adjusting ylim with stat_summary)