在async.each中的Mongoose findOne

时间:2015-09-11 06:30:16

标签: asynchronous mongoose

我想遍历一个数组并检查对象是否存在于mongodb中,然后插入或更新。

我正在使用async.each,然后在其中调用Model.findOne。但是findOne永远不会被执行。

exports.ProcessNasVirtualDevices = function ProcessNasVirtualDevicesInfo     (virtualDevices, callback)
{
    console.log("Started Virtual Devices");
    var virtualDeviceIds = [];
    if (virtualDevices != null) {
        //Loop through the virtual devices

        async.each(virtualDevices, function (objVirtualDevice, cb) {
            NasVirtualDevice.findOne({ VirtualDeviceName: nasVirtualDeviceName, PhysicalDeviceName: nasPhysicalDeviceName }, function (err, virtualDevices) {
                if (err) {
                    cb("", err);
                }
                else {
                    console.log("Found Virtual Device");
                    if (virtualDevices) {
                        console.log(nasVirtualDeviceName + "  found");
                        for (virtualDeviceProps in objVirtualDevice) {
                            console.log("Properties - " + virtualDeviceProps);
                            virtualDevices[virtualDeviceProps] = objVirtualDevice[virtualDeviceProps];
                        }
                        virtualDevices.save(function (err) {
                            if (err) {
                                cb("", err);
                            }
                            console.log("NasVirtualDevice " + objVirtualDevice.VirtualDeviceName + " updated");
                            cb();
                        });
                    }
                    else {
                        var nasVirtualDevice = new NasVirtualDevice();
                        for (virtualDeviceProps in objVirtualDevice) {
                            console.log("Properties - " + virtualDeviceProps);
                            nasVirtualDevice[virtualDeviceProps] = objVirtualDevice[virtualDeviceProps];
                        }
                        nasVirtualDevice.save(function (err) {
                            if (err) {
                                cb("", err);
                            }
                            console.log("NasVirtualDevice " + objVirtualDevice.VirtualDeviceName + " added");
                            cb();
                        });
                    }
                }            
            });                
        }, function (err) {
            // if any of the file processing produced an error, err would equal that error
            if (err) {
                // One of the iterations produced an error.
                // All processing will now stop.
                console.log('A Nas Virtual Device Failed');
            } else {
                console.log('All Virtual Device completed successfully');
            }                
        });
        callback("Nas Virtual Devices Completed");            
    }        
}

0 个答案:

没有答案