我正在尝试从mongodb数组中提取对象。
这是我的架构,
var VendorSchema = new Schema({
_id: {
type: Schema.Types.ObjectId,
ref: "User"
},
service_orders: {
pending_approval: [{
service_order: {
type: Schema.Types.ObjectId,
ref: "ServiceOrder"
},
package: {
type: Schema.Types.ObjectId,
ref: "ServicePackage"
}
}]
}
)}
我的问题是,
var marked_vendors =[ 5a76c4566b0e8c261cc47496, 5b05380f1cab52045c2afc1a ]
Vendor.update({ '_id': { $in: marked_vendors } }, { $pull: { 'service_orders.pending_approval.service_order': req.body.serviceorder_id } }, { new: true }).exec(function(err, vendors) {
if (err) {
console.log(err);
return res.json({ success: false, msg: err });
} else {
return res.json({ success: true, msg: 'Successfully pulled' });
}
});
但问题是,有时'service_orders.pending_approval'可以是一个空数组。它给了我以下错误
{
"success": false,
"msg": {
"name": "MongoError",
"message": "Cannot use the part (service_order) of (service_orders.pending_approval.service_order) to traverse the element ({pending_approval: []})",
"driver": true,
"index": 0,
"code": 28,
"errmsg": "Cannot use the part (service_order) of (service_orders.pending_approval.service_order) to traverse the element ({pending_approval: []})"
}
}
不可能使用try catch块来跳过错误。 那么有人可以帮我解决这个问题吗?