node.js - 如何使用 mongoose 和 nodejs 删除模型中关于 id 的项目

标签 node.js mongodb mongoose mongoose-schema

这是我的模式

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) {
    });         

});

如何根据 id 删除 purchaseOrderSchema 中的项目。 项目使用 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);
    }
);

关于node.js - 如何使用 mongoose 和 nodejs 删除模型中关于 id 的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35861442/

相关文章:

ruby-on-rails - 使用 MongoMapper 继承 : searching the parent class

mongodb - 如果数组包含匹配值,则查找 mgo 文档

node.js - Mongodb 从数组内的数组中提取对象

node.js - 来自 mongoDB 的空 [] 响应是 Node.js express get 函数的结果?

Typescript Mongoose 在 VS Code 中获取架构字段的 IntelliSense 或警告

node.js - 通过 aws codebuild 为 nodejs lambda 创建 zip 文件的问题

javascript - 在子模块中更好地使用 require()

javascript - 使用 Node-MySQL 时 ES6 Promise 乱序

node.js - 测试 Microsoft Bot Framework 异步回复

mongodb - 空数组阻止文档出现在查询中