代码之家  ›  专栏  ›  技术社区  ›  maison.m

mongoose-model.deleteone()正在删除整个集合,而不是单个文档

  •  3
  • maison.m  · 技术社区  · 6 年前

    我有一个包含一系列客户的用户模型。我想根据 customer _id . 从我在Mongoose文档中看到的,我应该使用 Model.deleteOne 删除单个文档。

    这是我的尝试

    用户架构(为简洁起见,已将其缩短):

    const mongoose = require('mongoose');
    
    const UserSchema = new mongoose.Schema({
        username: {
            type: String,
            default: ''
        },
        password: {
            type: String,
            default: '',
        },
        registerDate: {
            type: Date,
            default: Date.now()
        },
        customer: [{
            name: {
                type: String,
                default: '',
            },
            email: {
                type: String,
                default: 'No email name found'
            },
            fleet: [{
                unitNumber: {
                    type: String,
                    default: 'N/A',
                }
            }]
        }]
    });
    
    module.exports = mongoose.model('User', UserSchema);
    

    以下是路线和控制器:

    const express = require('express');
    const router = express.Router();
    
    const customer_controller = require('../../controllers/customers');
    
    router.delete('/customers/:custid', customer_controller.customer_remove);
    
      module.exports = router;
    

    最后是控制器:

    exports.customer_remove = (req, res) => {
        const { params } = req;
        const { custid } = params;
    
        User.deleteOne({ 'customer._id': custid }, (err) => {
            if (err)
                throw err;
            else 
                console.log(custid, 'is deleted');
        });
    };
    

    从我的想法来看, User.deleteOne({ 'customer.id': custid }) 会找到 顾客至上 匹配 custid 通过 req.params 。当我在postman中测试这个路由时,它会删除整个 User 客户所在的集合,而不仅仅是删除客户。我能往正确的方向推一下吗?我觉得我离这里很近(或不是lol)。

    2 回复  |  直到 6 年前
        1
  •  1
  •   JohnnyHK    6 年前

    deleteOne 在文档级别操作,因此您的代码将删除第一个 User 包含 customer 具有匹配项的元素 _id .

    相反,你想要 更新 要从中移除特定元素的用户文档 顾客 数组字段使用 $pull 。要从所有用户中删除客户:

    User.updateMany({}, { $pull: { customer: { _id: custid } } }, (err) => { ...
    
        2
  •  0
  •   Raunik Singh    6 年前

    使用猫鼬你可以做到这一点:

     model.findOneAndUpdate({ 'customer._id': custid }, {$pull: { $pull: { 
     customer: { _id: custid } }}, {new: true}).lean();
    

    正在删除子文档。

    默认情况下,每个子文档都有一个ID。Mongoose文档数组有一个特殊的ID方法,用于搜索文档数组以查找具有给定ID的文档。

    参观: https://mongoosejs.com/docs/subdocs.html

    parent.children.id(_id.remove());