He guys, storing an customer-Order in the Mongodatabase. Every Order has one or more user-created "drafts" inside, which are subdocuments with their own ID. The idea is to make them available separately without involving the order itself in any way. But I can't figure how to actually search for the single subdocument by id.
My Model looks like this:
var mongoose = require('mongoose');
var orderDraftSchema = mongoose.Schema({
name: String,
color: String,
price: Number,
attributes: []
});
var orderSchema = mongoose.Schema({
date: Date,
value: Number,
status: String,
customer: {},
drafts: [orderDraftSchema]
})
module.exports = mongoose.model('Orders', orderSchema);
How does my search have to look like? And do I need to export the subschema as well? Am I searching for my subschema, or the parentschema?
This feels very cluncy and unperformant, would love to have a more elegant solution:
var Order = require("../models/order.js");
getDraft: function(draftId, cb) {
Order.find({
drafts: {
$elemMatch: {
_id: {
$in: draftId
}
}
}
}, function(err, results) {
if (err) {
cb('No Matching Order found!');
} else {
var drafts = results[0].drafts;
var resultDraft;
for (i in drafts) {
if (drafts[i]._id == draftId) {
resultDraft = drafts[i];
}
}
console.log(resultDraft);
cb(resultDraft);
}
});
}