如何使用mongoose和nodejs删除模型中的项目id

这是我的模式

var purchaseOrderModel = function () { var itemSchema = mongoose.Schema({ strBarCode: {type: String }, strItemName: {type: String }, strQuantity: {type: String } }); var purchaseOrderSchema = mongoose.Schema({ strSupplierID: {type: String, required: true }, strInvoiceNo: {type: String,required: true }, dteInvoiceDate: {type: Date, required: true }, items: [itemSchema], created_by: { type: mongoose.Schema.Types.ObjectId, ref: 'user' } }); return mongoose.model('purchaseorder', purchaseOrderSchema); }; PurchaseOrder.find({items._id:req.params.itemid}, function (err, items) { return items.remove(function (err) { }); }); 

purchaseOrderSchema中如何删除id中的项目。 项目使用itemSchema存储。

您可以使用$pull更新操作符从数组中删除项目,如下所示:

 PurchaseOrder.update( { "items._id": req.params.itemid }, { "$pull": { "items": {"_id": req.params.itemid} } }, function (err, doc) { if(err) { /* handle err */} console.log(doc); } );