猫鼬.pull不会删除子文档

时间:2019-02-22 05:16:03

标签: mongodb express 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'
     } 
  ],
}

1 个答案:

答案 0 :(得分:0)

您可以尝试一下吗?

void foo(std::uint8_t* line) {
  assert(!(line % std::hardware_constructive_interference_size));
  prefetch(bytes + std::hardware_constructive_interference_size);
  auto result = bar(line);
  write(bytes + std::hardware_constructive_interference_size);
}

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