depperm
depperm

Reputation: 10746

Mongodb not updating

I have a collection Trips and I want to be able to add a passenger to the passenger array or create an array with a passenger. This SO answer mentions $push but even though node logs reserved seat on the trip and the front end has an alert with Your seat has been reserved the collection isn't updated (there is no passenger array in the Trips collection).

//reserve a seat for a trip
app.post('/api/trips/:trip/:passenger',function(req,res){
    console.log('trip:'+req.params.trip)
    console.log('passenger:'+req.params.passenger)
    db.collection('Trips').update({'_id':req.params.trip},{ $push: { "passengers": req.params.passenger }},function(err,res){
        if(err) throw err

        console.log('reserved seat on the trip')
    })
    res.send('Your seat has been reserved')

})

Mongo 3.2.11

Node 9.4.0

Express 4.15.5

Is there something wrong with my MongoDB call? Am I missing a step?

Upvotes: 1

Views: 3769

Answers (2)

depperm
depperm

Reputation: 10746

Based on @Veeram comments you need to pass the correct type, in this case ObjectId.

The correct code looks like:

var ObjectId = require('mongodb').ObjectID;

//reserve a seat for a trip
app.post('/api/trips/:trip/:passenger',function(req,res){
    console.log('trip:'+req.params.trip)
    console.log('passenger:'+req.params.passenger)
    db.collection('Trips').update({'_id':ObjectId(req.params.trip)},{ $push: { "passengers": req.params.passenger }},function(err,res){
        if(err) throw err

        console.log('reserved seat on the trip')
    })
    res.send('Your seat has been reserved')

})

Upvotes: 2

Prashant Mall
Prashant Mall

Reputation: 37

Currently I am working on a project which involves node.js and mongodb. The best way I have seen so far to post/get data from database is using mongoose.

This is the post part of my server.js file.

app.post('/description', (req, res) => {

  var DescriptionModel = new descriptionModel({
    header: req.body.header,
    header_image: req.body.header_image,
    sub_heading: req.body.sub_heading,
    sub_heading_tagline: req.body.sub_heading_tagline,
    sub_heading_image_path: req.body.sub_heading_image_path,
    sub_heading_data: req.body.sub_heading_data,
    paralax_image_heading: req.body.paralax_image_heading,
    paralax_image_tagline: req.body.paralax_image_tagline,
    gallary_heading: req.body.gallary_heading,
    gallary_tagline: req.body.gallary_tagline,
    gallary_image_path: req.body.gallary_image_path
  });

  DescriptionModel.save().then((doc) => {
    res.send(doc);
  }, (e) => {
    res.status(400).send(e);
  })
});

I am taking data from the post html body, you can directly enter your data.

I have created a schema file which I have imported.

If you need more help please ask in comments, I'll be happy to explain in more detail.

Upvotes: 0

Related Questions