【问题标题】:Mongoose .pull not deleting subdocumentMongoose .pull 不删除子文档
【发布时间】:2019-07-16 03:47:31
【问题描述】:

我正在尝试使用 mongoose 从类别中删除产品。从这些其他问题中删除,但似乎没有任何效果

Remove sub-document from Mongo with mongoose

但什么都没有发生,我只得到未经编辑的相同内容

类别架构

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const Product = require('./Product');

const CategorySchema = Schema({
  _id: Schema.Types.ObjectId,
  categoryName: {
    type: String,
    required: true,
  },
  categoryDescription: String,
  productList: [Product],
});

mongoose.model('Category', CategorySchema);

产品架构

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ProductSchema = Schema({
  productName: {
    type: String,
    required: true,
  },
  productDescription: String,
  categories: { type: Schema.Types.ObjectId, ref: 'Category' },
});

mongoose.model('Product', ProductSchema);

我处理删除子文档的快捷方式

app.delete('/api/category-with-product/:categoryId', (req, res) => {
    const categoryId = req.params.categoryId;
    const { productId } = req.body;

    Category.findById(categoryId)
      .then((category) => {
        category.productList.pull({ _id: productId });
        return category.save();
      })
      .then((newCategory) => {
        res.send(newCategory);
      });
  });

我的预期结果是只删除 productList 数组中的产品

{
  _id: 5c5b990d56b3f61ce3736e6f,
  categoryName: 'A new category name',
  description: 'description',
  productList:[
     { _id: 5c6e4b5114333b25f8e9d737,
       productName: 'test',
       productDescription: 'test'
     } 
  ],
}

【问题讨论】:

    标签: mongodb express mongoose


    【解决方案1】:

    你能试试这个吗:

    const ObjectId = mongoose.Types.ObjectId;
    function funcName() {
        return new Promise((resolve, reject) => {
          db.category.update(
               { },
               { $pull: { productList: { _id: ObjectId(productId) } } },
               { multi: true }
          )
            .then((result) => resolve())
            .catch((err) => reject(err));
        });
      }
    

    您也可以在数据库操作期间尝试 Async/Await。

    【讨论】:

    • 我现在收到这个错误“UnhandledPromiseRejectionWarning: MongooseError: Callback must be a function, got [object Object]”你知道怎么解决吗?
    • 问题在于回调。尝试使用 promise 或 async/await 来解决答案中更新的问题。
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2021-02-10
    • 2019-05-27
    • 2016-09-12
    • 1970-01-01
    • 2019-01-01
    相关资源
    最近更新 更多