While I am adding values to a sub document, in command prompt it shows the error
like cannot read property push
. How can I solve this?
Here's my schema code
with the help of these I gave values to parent schema
but I'm not able to give the values to this sub document:
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
});
And my 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);
});
});
})
Here parent document is batchSchema
and sub-document is venueSchema
. After
creation of batch I will get an id
. With the help of this id
I am trying to add values to venue at that time it shows me the error atbatch.venue.push(req.body);
To resolve your TypeError: Cannot read properties of undefined (reading '0') , go through these steps: Ensure you are using the correct variable. Perform a simple check on your variable before using it to make sure it is not undefined. Create a default value for the variable to use if it does happen to be undefined.
To fix the "Cannot read property 'push' of undefined" error with React Router, we should call the withRouter component with our route component so the history object is available in the props. import { withRouter } from "react-router"; class App extends Component { push = () => { this. props. history.
What Causes TypeError: Cannot Read Property of Undefined. Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects.
The "Cannot read property '0' of undefined" error occurs when trying to access the 0th index in a variable that stores an undefined value. Make sure to initialize the variable to the correct type, e.g. array or string, before accessing the index.
Router();
In this method If we are not mention () this also it will show the push error...
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With