cuốn sách gpt4 ai đã làm

node.js - 如何在 MongoDB collection.find() 上获得回调

In lại Tác giả: Hồ Xil 更新时间:2023-11-01 09:55:14 27 4
mua khóa gpt4 Nike

当我在 MongoDB/Node/Express 中运行 collection.find() 时,我想在它完成时得到一个回调。正确的语法是什么?

 function (id,callback) {

var o_id = new BSON.ObjectID(id);

db.open(function(err,db){
db.collection('users',function(err,collection){
collection.find({'_id':o_id},function(err,results){ //What's the correct callback synatax here?
db.close();
callback(results);
}) //find
}) //collection
}); //open
}

câu trả lời hay nhất

这是正确的回调语法,但是 find 提供给回调的是 Cursor ,而不是文档数组。因此,如果您希望回调以文档数组的形式提供结果,请调用 toArray在光标上返回它们:

collection.find({'_id':o_id}, function(err, cursor){
cursor.toArray(callback);
db.close();
});

请注意,您的函数的回调仍然需要提供一个 err 参数,以便调用者知道查询是否有效。

2.x 驱动更新

find 现在返回光标而不是通过回调提供光标,因此典型用法可以简化为:

collection.find({'_id': o_id}).toArray(function(err, results) {...});

或者在这种需要单个文档的情况下,使用 findOne 会更简单:

collection.findOne({'_id': o_id}, function(err, result) {...});

关于node.js - 如何在 MongoDB collection.find() 上获得回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33251290/

27 4 0
Hồ Xil
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress