使用mongoose返回错误删除子文档?

时间:2017-01-09 13:11:03

标签: node.js mongodb mongoose

我想删除我收藏的所有子文档。

mongoose架构:

   //productSchema
    var pdtSchema = new Schema({
        "productId"     : {type : String},
        "product"       : {type : String},
        "item no"       : {type : String},
        });

    var shopSchema = new Schema({
        "providerId"    : {type : String},
        "provider"      : {type : String},
        "products"      : [pdtSchema]
    },{collection:"shopdetails"});

    module.exports.Shops    = mongoose.model('Shops',shopSchema);
    module.exports.Products = mongoose.model('Products',pdtSchema);

我在集合中存储了大量数据,我需要删除所有产品(即整个pdtSchema数据)。

router.post('/delete',function (req,res) {
   var providerId = req.body.providerId;
   model.Shops.findById({"providerId" : providerId},function(err, doc) {     
     console.log(doc.products) // returns whole products here...
     doc.products.remove();
     doc.save(function(err,data){
       res.json({"msg":"deleted"});
    });
   });
 });

错误:

(node:16351) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ValidationError: CastError: Cast to ObjectID failed for value "[Function]" at path "_id"

2 个答案:

答案 0 :(得分:1)

使用$unset运算符,使用 findOneAndUpdate() 方法删除E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.zeba.broccoli, PID: 1231 android.content.res.Resources$NotFoundException: Resource ID #0x1 at android.content.res.Resources.getValue(Resources.java:2452) at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:330) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:195) at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:188) at android.support.v7.content.res.AppCompatResources.getDrawable(AppCompatResources.java:100) at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:73) at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:81) at android.widget.SimpleAdapter.setViewImage(SimpleAdapter.java:262) at android.widget.SimpleAdapter.bindView(SimpleAdapter.java:192) at android.widget.SimpleAdapter.createViewFromResource(SimpleAdapter.java:126) at android.widget.SimpleAdapter.getView(SimpleAdapter.java:114) at android.widget.AbsListView.obtainView(AbsListView.java:2828) at android.widget.ListView.measureHeightOfChildren(ListView.java:1292) at android.widget.ListView.onMeasure(ListView.java:1204) at android.view.View.measure(View.java:18870) at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728) at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464) at android.view.View.measure(View.java:18870) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908) at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:703) at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90) at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1367) at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:768) at android.view.View.measure(View.java:18870) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908) at android.widget.FrameLayout.onMeasure(FrameLayout.java:436) at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139) at android.view.View.measure(View.java:18870) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435) at android.widget.LinearLayout.measureVertical(LinearLayout.java:721) at android.widget.LinearLayout.onMeasure(LinearLayout.java:612) at android.view.View.measure(View.java:18870) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908) at android.widget.FrameLayout.onMeasure(FrameLayout.java:436) at android.view.View.measure(View.java:18870) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435) at android.widget.LinearLayout.measureVertical(LinearLayout.java:721) at android.widget.LinearLayout.onMeasure(LinearLayout.java:612) at android.view.View.measure(View.java:18870) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908) at android.widget.FrameLayout.onMeasure(FrameLayout.java:436) at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:3076) at android.view.View.measure(View.java:18870) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2392) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1416) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1661) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1301) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7016) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777) at android.view.Choreographer.doCallbacks(Choreographer.java:590) at android.view.Choreographer.doFrame(Choreographer.java:560) at android.view.Choreographer$FrameDisplayEventRec I/Process: Sending signal. PID: 1231 SIG: 9 Application terminated. 字段。首先使用传统方法 使用 findById() 检索文档只能使用有效的products,在您的情况下,您只提供非ObjectId字符串,因此会出错。

ObjectId

如果您想保留数组字段但删除其所有元素,请使用 $set 作为

router.post('/delete',function (req,res) {
    var providerId = req.body.providerId;
    model.Shops.findOneAndUpdate(
        { "providerId": providerId },
        { "$unset": { "products": "" } },
        { "new": true }
        function(err, doc) {     
            console.log(doc) // returns modified doc here...
            res.json({"msg": "Field deleted"});
        }
    );
 });

答案 1 :(得分:1)

这是因为您将shopSchema中的“providerId”保存为String类型,即使它是一个猫鼬对象。 因此,将字符串类型与mognoose ObjectId类型进行比较会产生强制转换错误。

而是这样做,

var shopSchema = new Schema({
        "providerId"    : {
               type : Schema.ObjectId
               ref : schema which they are a reference to},
        "provider"      : {type : String},
        "products"      : [pdtSchema]
    },{collection:"shopdetails"});

但是,我认为如果providerId引用商店ID,那么它应该只是_id。

model.findById()适用于_id