如何解决 cannot read 属性 'push' of undefined in nodejs application?

How to solve cannot read property 'push' of undefined in nodejs application?

当我向子文档添加值时,在命令提示符下显示错误
就像无法阅读 属性 push。我该如何解决这个问题?

这里是 my schema code 在这些的帮助下我给父模式赋值
但我无法为该子文档提供值:

var venueSchema = new Schema({
    name:  {
        type: String,
        required: true,
        unique:true
    },
    address:  {
        type: String,
        required: true
    }
}, {
    timestamps: true
});

// create a schema
var batchSchema = new Schema({
   batchname: {
        type: String,
        required: true,
        unique: true
    },
    activityname: {
        type: String,
        required: true
    },
    time: {
    type:String,
    required:true
    },
    duration: {
    type:String,
    required:true
    },
    classtype: {
    type:String,
    required:true
    },
    trainer: {
    type:String,
    required:true
    },
    price:{
    type:Currency,
    required:true,
    unique:true
    },

    venue:[venueSchema]
}, {
    timestamps: true
});  

还有我的Routing code

batchRouter.route('/:batchId/venue')
.post(function (req, res, next) {
    Batches.findById(req.params.batchId, function (err, batch) {
        if (err) throw err;
      batch.venue.push(req.body);
        batch.save(function (err, batch) {
            if (err) throw err;
            console.log('Updated venue!');
            res.json(batch);
        });
    });
})

此处父文档为batchSchema,子文档为venueSchema。之后
创建批次我会得到一个 id。在 id 的帮助下,我当时正在尝试向场地添加值,它显示
处的错误 batch.venue.push(req.body);

您得到的错误意味着:

  1. 你没有从数据库中得到错误,因为 if (err) throw err; 没有触发
  2. 您的 batch.venue 未定义,因为您得到 Cannot read property 'push' of undefined
  3. 你的batch被定义了,因为你没有得到Cannot read property 'venue' of undefined

这意味着你与数据库建立了连接,你得到了一个带有你想要的 ID 的文档,但它没有你希望出现的 属性 venue并成为一个数组。

而不是:

batch.venue.push(req.body);

您可以使用:

if (!Array.isArray(batch.venue)) {
    batch.venue = [];
}
batch.venue.push(req.body);

或:

if (Array.isArray(batch.venue)) {
    batch.venue.push(req.body);
} else {
    batch.venue = [req.body];
}

或类似的东西,即您需要在尝试将元素推送到数组之前检查是否有数组。如果您没有数组,则必须创建一个新数组。

这也可以这样解决:

Batches.findById(req.params.batchId, function (err, batch) {
    if (err) throw err;
  const a = req.body.venue;
  for(i=0;i<a.length;i++ )
  {
   batch.venue.push(req.body.venue[i]);
  }

    batch.save(function (err, batch) {
        if (err) throw err;
        console.log('Updated venue!');
        res.json(batch);
    });
});

路由器();

在这个方法中如果我们没有提到() this 也会显示推送错误...

const express = require('express');
const routerd = express.Router();
const Ninja = require('./models/ninja');

routerd.delete('/ninja:/id', function(req, res, next){
    console.log(req.params.id);
    res.send({type : 'DELETE'});
}).catch(next);

module.exports = routerd;

当我们没有正确导入路由器时出现此错误。

示例代码片段

const express = require('express')
const router = express.Router();

router.get("/signout", (req, res) =>{
  res.send("user sign out")
 })


module.exports = router;