Saturday 18 March 2017

Unable to return _id of a subdocument using mongoosejs

[
{
    "_id": "58b89de6a480ce48c8f3742d",
    "name": "Core Site",
    "version": "1.0.0",
    "author": "Jane Doe",
    "vendor": "Online Banking",
    "steps": [
        {
            "name": "Step 1: Fun Stuff",
            "dependencies": "1,2,3,4",
            "resource": "TS",
            "weight": 0
        },
        {
            "name": "Step 2: Weird Stuff",
            "dependencies": "3,4",
            "resource": "PS",
            "weight": 1
        }
    ]
},
{
    "_id": "58b8a22097fbe41746827ac7",
    "name": "Online Statements",
    "version": "1.0.0",
    "author": "John Doe",
    "vendor": "Online Banking",
    "steps": [
        {
            "name": "Step 1: Fun Stuff",
            "dependencies": "1,2,3,4",
            "resource": "TS",
            "weight": 0
        }
    ]
}]

I have saved this information into a MongoDB but when I try to get this information the sub-document "Steps" does not include the _id that I can see using Robomongo.

My schema is as follows:

    // grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var stepSchema = new Schema({
  name: { type: String, required: true},
  dependencies: String,
  resource: String,
  weight: Number
})

// create a schema
var sopSchema = new Schema({
  name: { type: String, required: true, unique: true },
  version: String,
  author: String,
  vendor: String,
  steps: [stepSchema]
});



// the schema is useless so far
// we need to create a model using it
var Sop = mongoose.model('Sop', sopSchema);

// make this available to our users in our Node applications
module.exports = Sop;

My end goal is to check if the step is already included and update it when making a change on the front end. So i wanted to get this reference to ensure i have the right subdocument.

My get statement is as follows in my nodejs server.

router.route('/sops')
    .get(function(req, res) {
        Sop.find(function(err, sops) {
            if (err)
                res.send(err);

                var subdoc = sops[0].steps[0];
                console.log(subdoc);
            res.json(sops);
    });
})



via Ben Gummelt

No comments:

Post a Comment