TypeError:使用findOneAndRemove()

时间:2019-03-29 06:44:34

标签: node.js express mongoose

当我执行函数findOneAndRemove()并传递所需的参数时,它显示错误“ TypeError:无法读取未定义的属性'_id'”。我的mongodb具有属性'_id'

我尝试了findById()。它正在工作,但是如果我定义了findOneAndRemove({_ id:req.params.id}),则会发生错误。

**router**

router.delete('/delete/:id', async (req, res) => {
    try {
        var id = req.params.id;

        if (!ObjectID.isValid(id))
            return res.status(404).send();

        let team = await Team.findOneAndDelete({ _id: id, createdBy: req.user._id });
        console.log('team', team);
        if (!team)
            return res.status(404).send();

            res.status(201).json({
              message: 'Team Deleted',
              result: { team }
            });
    } catch (e) {
        console.log(e);
        res.status(400).send(e);
    }
  });
**Team Model**

var mongoose = require('mongoose');

const teamSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  country: {
    type: String,
    required: true,
    trim: true
  },
  yearFounded: {
    type: Date,
    required: true
  },
  ground: {
      type: String,
      required: true,
      trim: true
  },
  capacity: {
      type: Number,
      required: true,
  },
  manager: {
    type: String,
    required: false,
  },
  website: {
    type: String,
    required: false,
  },
  imagePath: {
    type: String,
    required: false,
  },
  description: {
    type: String,
    required: false
  },
  createdBy: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      ref: 'User'
  }
}, {
  timestamps: true
})


teamSchema.index({ name: "text", manager: "text", ground: "text", country: "text" });

teamSchema.virtual('players', {
  ref: 'Player',
  localField: '_id',
  foreignField: 'team'
})


const Team = mongoose.model('Team', teamSchema);

module.exports = Team


2 个答案:

答案 0 :(得分:1)

findOneAndRemove返回已删除的文档,因此,如果删除了以后决定不删除的文档,则可以将其重新插入数据库。在删除文档之前,请确保逻辑合理,而不是在事后检查IMO。

findOneAndDelete具有sort参数,可用于影响哪个文档被更新。它还具有一个TimeLimit参数,该参数可以控制必须完成的操作

尝试

    router.delete('/delete/:id', async (req, res) => {
    try {
        let id = {_id:req.params.id};

        if (!ObjectID.isValid(id))
            return res.status(404).send();

        let team = await Team.findOneAndRemove({ _id: rid, createdBy: req.user._id });
        console.log('team', team);
        if (!team)
            return res.status(404).send();

            res.status(201).json({
              message: 'Team Deleted',
              result: { team }
            });
    } catch (e) {
        console.log(e);
        res.status(400).send(e);
    }
});

答案 1 :(得分:0)

答案是我忘记添加中间件“身份验证”,因此createdBy参数req.user._id永远是不确定的。解决方案。

路线

router.delete('/delete/:id', authenticate, async (req, res) => {
    try {
        var id = req.params.id;

        if (!ObjectID.isValid(id))
            return res.status(404).send();

        let team = await Team.findOneAndRemove({ _id: id, createdBy: req.user._id });
        if (!team)
          return res.status(404).send();

        removeImage(team.imagePath);
        res.status(201).json({
          message: 'Team Deleted',
          result: { team }
        });
    } catch (e) {
        console.log(e);
        res.status(400).send(e);
    }
  });

中间件

let authenticate = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer ', '')
        const decoded = jwt.verify(token, process.env.JWT_SECRET)
        const user = await User.findOne({ _id: decoded._id, 'tokens.token': token })

        if (!user) {
            throw new Error()
        }

        req.token = token;
        req.user = user;
        next()
    } catch (e) {
        res.status(401).send({ error: 'Please authenticate.' })
    }
};