简体   繁体   中英

Mongoose Delete SubDocument in Array

i am using mongoose to make database for my project, my schema Class has structure like this:

const mongoose = require('mongoose')

const classSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  consultant: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Consultant',
    required: true
  },
  startYear: {
    type: String,
    required: true
  },
  classname: {
    type: String,
    required: true,
    unique: true
  },
  studentList: [
    {
      code: {
        type: String,
        required: true
      },
      fullname: {
        type: String,
        required: true
      }
    }
  ]
})

const Class = mongoose.model('Class', classSchema)

module.exports = Class

as you can see, i have a property called studentList is an array and this is how it was store in mongoose Atlas

猫鼬

so now i want to delete a subdocument in array studentList so this is my route:

http://localhost:5000/users/:code

and this is how i have done:

    exports.delele_student_from_user = (req, res, next) => {
      var { code } = req.params;
      var { classname } = req.body;
    
      User.findOneAndDelete({
        classname,
        studentList: {
          $pull: {
            code,
          },
        },
      })
        .exec()
        .then((doc) => {
          console.log(`deleted user with code ${code} from colection User`);
          next();
        })
        .catch((err) => {
          console.log(err);
          return res.status(500).json({ err });
        });
    };

and i got this Error:

{ MongoError: unknown operator: $pull
    at MessageStream.messageHandler (C:\Users\ASUS\OneDrive\Desktop\uet-backend\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:266:20)
    at MessageStream.emit (events.js:198:13)
    at processIncomingData (C:\Users\ASUS\OneDrive\Desktop\uet-backend\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:144:12)
    at MessageStream._write (C:\Users\ASUS\OneDrive\Desktop\uet-backend\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:42:5)
    at doWrite (_stream_writable.js:415:12)
    at writeOrBuffer (_stream_writable.js:399:5)
    at MessageStream.Writable.write (_stream_writable.js:299:11)
    at TLSSocket.ondata (_stream_readable.js:709:20)
    at TLSSocket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at TLSSocket.Readable.push (_stream_readable.js:224:10)
    at TLSWrap.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
  operationTime:
   Timestamp { _bsontype: 'Timestamp', low_: 3, high_: 1603874496 },
  ok: 0,
  code: 2,
  codeName: 'BadValue',
  '$clusterTime':
   { clusterTime:
      Timestamp { _bsontype: 'Timestamp', low_: 3, high_: 1603874496 },
     signature: { hash: [Binary], keyId: [Long] } },
  name: 'MongoError' }
DELETE /students/16022267 500 785.904 ms - 240

please show me how to fix this, thank you so much and have a good day

Use findOneAndUpdate() \\

You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pull or $pullAll operators to remove the item from the array.

https://docs.mongodb.com/manual/reference/operator/update/pull/#up._S_pull

You need to use update

exports.delele_student_from_user = async (req, res, next) => {
  var { code } = req.params;
  var { classname } = req.body;
  try {
    await User.update(
      { classname },
      {
        $pull: {
          studentList: { code }
        }
      }
    );
    return res.status(200).json({ message: "Student deleted" });
  } catch (err) {
    return res.status(500).json({ err });
  }
};

I have also used async / await so it looks cleaner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM