使用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 thereg_result
variable it returnsundefined
. What should I do to correct this?I debugged using
console.log
on theuser.js
and theitem
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
最满意答案
出于一个简单的原因,您不会找到关于
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>
andHashSet<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
forList<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 forQueue<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; }
相关问答
更多-
.NET ConcurrentDictionary.ToArray()ArgumentException(.NET ConcurrentDictionary.ToArray() ArgumentException)[2023-09-12]
这是因为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(..)),在执行初始查询之前在 ...
-
值或者抛出异常(Value or else throw exception)[2022-09-28]
throw是一个语句,因此不能在需要表达式的地方使用它。 您可以创建一个只抛出错误的函数,然后将该函数作为表达式的一部分调用: function throwMissing ( ) { throw new Error( 'missing' ); } 当你想抛出错误时: var x = lookupSomeValue() || throwMissing(); 当然你也可以使用匿名函数: var x = lookupSomeValue() || function(){ throw new Error ...