如何解决无法读取nodejs应用程序中未定义的属性'push'?

问题描述 投票:3回答:3

虽然我正在向子文档中添加值,但在命令提示符下显示错误就像无法读取属性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);

node.js mongodb mongoose-schema
3个回答
3
投票

您收到的错误表示:

  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];
}

或类似的东西,即您需要先检查是否有数组,然后再尝试将元素推入其中。如果没有数组,则必须创建一个新数组。


1
投票

这也可以解决为:

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);
    });
});

0
投票

Router();

在此方法中,如果我们不提及(),也会显示推送错误...

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;
© www.soinside.com 2019 - 2024. All rights reserved.