通过id查找并使用mongoose mongodb删除

时间:2018-11-04 16:31:43

标签: node.js mongodb mongoose

我是nodejs和mongodb的新手,我试图从类别文档中删除类别。类别文档包含用户文档的ObjectId。用户添加类别时,我将用户ID保存在类别文档中。

这是类别文档:

 {
    "isActive": true,
    "_id": "5bded03fe125544798039c2c",
    "name": "aaaaaaaa",
    "description": "test",
    "imageUrl": "test",
    "user": "5bdec5f94a9730439590a164",
    "__v": 0
}

用户架构:

 const UserSchema = new Schema({
 name: {
    type: String,
    required:true,
    minlength:3
 },
email: {
    type: String,
    required:true,
    minlength:5
},
 password: {
    type: String,
    required:true,
    minlength:6
 },
 isAdmin: {
    type: Boolean,
    default: false
 },
 date: {
    type: Date,
    default: Date.now
 }
});

类别架构:

const CategorySchema = new Schema({
user: {
    type: Schema.Types.ObjectId,
    ref: 'users'
},
name: {
    type: String,
    required:true
},
description: {
    type: String,
    required:true,
},
imageUrl: {
    type: String,
    required:true,
},
isActive: {
    type: Boolean,
    default: true
}
});

以下是我的删除请求代码:

router.delete('/:cat_id', (req, res) => {
   Category.findByIdAndRemove(req.params.cat_id)
    .then(() => {
        res.status(200).json({ message: 'Category deleted successfully!' 
   });
    }).catch(err => res.status(400).json(err));
  }); 

当我点击删除请求时,出现以下错误:

{
"message": "Cast to ObjectId failed for value \"5bded03fe125544798039c2cs\" at path \"_id\" for model \"categories\"",
"name": "CastError",
"stringValue": "\"5bded03fe125544798039c2cs\"",
"kind": "ObjectId",
"value": "5bded03fe125544798039c2cs",
"path": "_id"
}

我也尝试了此解决方案,但没有成功: https://stackoverflow.com/a/44147638/10603547 它给了我以下错误

 Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

我的代码有什么问题?谢谢

0 个答案:

没有答案