rf guy
rf guy

Reputation: 439

how to append document and update key

I am trying to implement a version control type database for record updates. I am using mongoose to do the heavy work. My model looks like the following:

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;

    const VenueSchema = new Schema({
        _id: String,
        num_revisions: {type: Number, default: 0},
        "1": {
            avp_prio: Number,
            prio_cat: String,
            mkt_prio: Number,
            comp_pos: String,
            pvc_driver: Number,
            pvc_desc: String
        }
    });

    const Venue = mongoose.model('venue', VenueSchema);

    module.exports = Venue;

The num_revisions will represent how many revisions have taken place. The Key "1" represent the revision the document is. My goal is to increment num_revisions after a put has occurred and append the res.body to the original document and match the key to the num_revisions value so I know exactly what document is the most recent.

Here is my PUT method thus far. I am able to inc the num_revisions fine but I am not sure how to append the req.body and update the key for it.

    /* PUT update docuement with new revision. */
    router.put('/:id', (req, res, next) => {
        console.log(req.body);
        Venue.findOneAndUpdate({ _id: req.params.id }, { $inc: { num_revisions: 1 },key: 2}, {new: true}).then(function (venue) {   
            res.send(venue);
        });
    });

Any help is greatly appreciated!

I am trying to complete the following:

{
  "_id": "testvenue",
  "__v": 0,
  "num_revisions": 2,
  "1": {
    "avp_prio": 1,
    "prio_cat": "text",
    "mkt_prio": 1,
    "comp_pos": "test",
    "pvc_driver": 1,
    "pvc_desc": "test"
  },
  "2": {
    "avp_prio": 3,
    "prio_cat": "update",
    "mkt_prio": 1,
    "comp_pos": "test",
    "pvc_driver": 1,
    "pvc_desc": "test"
  }
}

Upvotes: 0

Views: 32

Answers (1)

Akrion
Akrion

Reputation: 18525

You could simplify your life significantly if you revise you schema to this:

const VenueSchema = new Schema({
    _id: String,
    revisions: [{
        //... your props
    }]
});

This way the index of the array would be your key and the array length would simply be your num_revisions.

For the rest of your idea you should look into mongoose middleware and specifically the pre and post hooks. They are basically designed for what you are trying to get to. They fire events before and after save, update etc on models.

Upvotes: 1

Related Questions