通过Node MongoDB本机驱动程序使用Nodejs和MongoDB.需要检索一些文档并进行修改,然后将它们保存回来.这是一个例子:
db.open(function (err, db) {
db.collection('foo', function (err, collection) {
var cursor = collection.find({});
cursor.each(function (err, doc) {
if (doc != null) {
doc.newkey = 'foo'; // Make some changes
db.save(doc); // Update the document
} else {
db.close(); // Closing the connection
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
具有异步性质,如果更新文档的过程需要更长时间,那么当游标到达文档末尾时,数据库连接将关闭.并非所有更新都保存到数据库中.
如果db.close()省略,则所有文档都已正确更新,但应用程序挂起,永不退出.
我看到一篇帖子暗示使用计数器跟踪更新次数,当回落到零时,然后关闭数据库.但我在这里做错了吗?处理这种情况的最佳方法是什么?是否db.close()必须用来释放资源?或者是否需要打开新的数据库连接?
例如,如果我想在p元素上显示当前日期:
$("p").html('Now is '+Date()); // good
$("p").html('Now is '+new Date()); // good
$("p").html(Date()); // good
$("p").html(new Date()); // bad
Run Code Online (Sandbox Code Playgroud)
为什么最后一个语句不显示当前日期,但第二个语句有效?
有人可以帮我解释为什么第一个例子有效,但第二个例子没有.
// Define a class
function Foo(name) {
var self = this;
this.name = name;
this.greeting = function() {
console.log('Hello ' + self.name);
}
}
var foo = new Foo('foo');
foo.greeting();
var greeting = foo.greeting;
greeting();
Run Code Online (Sandbox Code Playgroud)
输出:
Hello foo
Hello foo
Run Code Online (Sandbox Code Playgroud)
// Define a class
function Foo(name) {
this.name = name;
}
// Greeting
Foo.prototype.greeting= function () {
console.log('Hello ' + this.name);
}
var foo = new Foo('foo');
foo.greeting();
var greeting = foo.greeting;
greeting();
Run Code Online (Sandbox Code Playgroud)
输出:
Hello foo
Hello …Run Code Online (Sandbox Code Playgroud)