I'm trying to establish a one to many relationship between "Result" and "Scan"
Result.js
var mongoose = require('mongoose');
var resultSchema = mongoose.Schema({
label: String,
version: String,
created_at: { type: Date, default: Date.now },
scans: [{type: mongoose.Schema.Types.ObjectId, ref: 'Scan'}]
});
var Result = mongoose.model('Result', resultSchema);
module.exports = Result;
Scan.js
var mongoose = require('mongoose');
var scanSchema = mongoose.Schema({
result: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Result'
},
file: String,
payloads: [String],
execution_time: Number
});
var Scan = mongoose.model('Scan', scanSchema);
module.exports = Scan;
api.js
router.post('/results', function(req, res, next) {
var result = new Result({
label: req.body.label || "Unknown Label",
version: req.body.version || "Unknown Version",
});
result.save(function(err, result) {
if (err) console.error(err);
for (var i = 0; i < req.body.scans.length; i++) {
var _scan = req.body.scans[i];
var scan = new Scan({
file: _scan.file || "Unknown File Name",
payloads: _scan.payloads || [],
execution_time: _scan.execution_time,
result: result._id
});
scan.save(function(err, scan) {
console.log(scan);
if (err) console.error(err);
});
}
res.json(result);
})
});
router.get('/results', function(req, res, next) {
Result.find({})
.populate('scans')
.exec(function(err, result) {
if (err) console.error(err);
res.json(result);
});
});
So my payload contains the details for a "Result" object along with an array of "Scan"(s) that belong to it. I want to be able to store the results and scans as separate collections so that I can query them independently of each other. Both requests don't error or write anything to the console. The post requests does indeed create a list of Result documents and a list of corresponding Scan documents. However, the get request doesn't seem to populate when returning the list of all the Result(s).
The other thing I'm trying to do is return the populated Result object when someone creates a result. Of course, each save of a Scan object is async so I need a way to see if "they are all done". I'd appreciate some best practices on that as well.
via Carpetfizz
No comments:
Post a Comment