首页 > 解决方案 > 如何从猫鼬用户模型模式中删除条目“对象”

问题描述

我已经弄清楚如何发出 PUT 请求以将 PDF 存储到我的“用户”模式。

我将如何coverLetter从“req.profile = user”访问该对象以仅在此用户的配置文件中发出删除此条目的请求。

我只设法弄清楚如何从数据库中删除整个用户或文档。

前端:React 后端:Node.js、express、MongoDB、Mongoose

感谢您的任何建议

后端


// Router defintions
router.delete("/user/documents/coverLetter/:userId", deleteData); 
router.param("userId", userById);

// Adds user to the Request object
exports.userById = (req, res, next, id) => {
  User.findById(id).exec((err, user) => {
    if (err || !user) {
      return res.status(400).json({
        error: "User not found",
      });
    }
    req.profile = user; // adds profile object in req with user info
    next();
  });
};


/** User Profile Object

{
  coverLetter: {
    contentType: 'application/pdf',
    data: Binary {
      _bsontype: 'Binary',
      sub_type: 0,
      position: 396412,
      buffer: <Buffer 25 50 44 46 2d 31 2e 33 0a 25 c4 e5 f2 e5 eb a7 f3 a0 d0 c4 c6 0a 34 20 30 20 6f 62 6a 0a 3c 3c 20 2f 4c 65 6e 67 74 68 20 35 20 30 20 52 20 2f 46 69 ... 396362 more bytes>
    }
  },
  _id: 60c2ef9e13f13d902a07ab0b,
  fName: 'gh',
  lName: 'h',
  email: 'b@gmail.com',
  salt: '73bb4607-47bf-407f-9155-0b65d19c21be',
  hashed_password: 'a3e08880687ec89344e2a5c6989b1f68bcceee1b',
  created: 2021-06-11T05:07:42.472Z,
  __v: 0,
  updated: 2021-06-11T05:08:01.099Z
}

*/


/**
* Need help with this block
*/
exports.deleteData = (req, res) => {
    let user = req.profile
    // How do I access the coverLetter to delete it ?
}

/**
* User Schema
*/
const userSchema = new mongoose.Schema({

    fName: {
        type: String,
        trim: true,
        required: true
    },
    lName: {
        type: String,
        trim: true,
        required: true

    },
    coverLetter: {
        data: Buffer,
        contentType: String,
    },
});

module.exports = mongoose.model("User", userSchema);

前端

export const deleteCover = (userId, token) => {
    return fetch(`${process.env.REACT_APP_API_URL}/user/documents/coverLetter/${userId}`, {
        method: "DELETE",
        headers: {
            Accept: "application/json",
            Authorization: `Bearer ${token}`
        }
    })
        .then(response => {
            return response.json();
        })
        .catch(err => console.log(err));
};

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


您可以使用$unset运算符对文档进行更新。

/**
 * Need help with this block
 */
exports.deleteData = (req, res) => {
  let user = req.profile
  // To remove the key you can use the '$unset' operator.
  user.update({
    '$unset': {
      'coverLetter': 1
    }
  })
}

或者,如果要避免使用 MongoDB 运算符,也可以将字段设置为undefined并调用save方法。

/**
 * Need help with this block
 */
exports.deleteData = (req, res) => {
  let user = req.profile
  user.coverLetter = undefined;
  user.save(callback);
}


推荐阅读