gpt4 book ai didi

javascript - node.js,测试 mongodb 保存和加载

转载 作者:行者123 更新时间:2023-11-30 13:24:34 25 4
gpt4 key购买 nike

也许我只是无法弄清楚回调,但我想不出一种方法来测试 node.js 中的保存和加载。

我的测试是这样的:

vows.describe('Saving').addBatch({
'Single item can be saved':{
topic:function () {
myStore.saveItems(1, [{id:3,name:'squat'}]);
myStore.getItems(1, this.callback);
},
'saved item is returned by getItems':function (err, items) {
assert.equal(items.length, 1);
assert.equal(items[0].deviceId, 1);
assert.equal(items[0].id, 3);
}
}
}).export(module);

经过测试:

exports.saveItems = function (deviceId, items) {
var itemsCollection = db.collection('items');

itemsCollection.find({deviceId:deviceId}).toArray(function (err, existingItems) {
_.each(items, function (item) {
item['deviceId'] = deviceId;
var existingItem = _.find(existingItems, function (existingItem) {
return existingItem.id === item.id
});
if (typeof(existingItem) === 'undefined') {
itemsCollection.save(item);//callback here?
} else {
}
});
});
};

exports.getItems = function (deviceId, callback) {
var itemsCollection = db.collection('items');
itemsCollection.find({deviceId:deviceId}).toArray(callback);
};

有没有一种方法可以将回调传递给 saveItems,这样 getItemsall mongo 保存完成之前不会被调用完成了吗?

最佳答案

试试这个:)

vows.describe('Saving').addBatch({
'Single item can be saved':{
topic:function () {
var topicThis = this;
// NEW: having a callback here
myStore.saveItems(1, [{id:3,name:'squat'}], function(err, results){
myStore.getItems(1, topicThis.callback);
});
},
'saved item is returned by getItems':function (err, items) {
assert.equal(items.length, 1);
assert.equal(items[0].deviceId, 1);
assert.equal(items[0].id, 3);
}
}
}).export(module);

// https://github.com/caolan/async
var async = require('async');
// NEW: having a callback here
exports.saveItems = function (deviceId, items, cb) {
var itemsCollection = db.collection('items');

itemsCollection.find({deviceId:deviceId}).toArray(function (err, existingItems) {
var tasks = [];
// here you are iterating over each item, doing some work, and then conditionally doing an async op
_.each(items, function (item) {
item['deviceId'] = deviceId;
var existingItem = _.find(existingItems, function (existingItem) {
return existingItem.id === item.id
});
if (typeof(existingItem) === 'undefined') {
// so this is async, b/c it's talking to mongo
// NEW: add it to our list of tasks, when are later run in parallel
tasks.push(function(nextTask){
itemsCollection.save(item, nextTask);
});
}
});
// NEW: run it all in parrallel, when done, call back
async.parallel(tasks, function(err, results) {
cb(err, results);
})
});
};

关于javascript - node.js,测试 mongodb 保存和加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8965070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com