Yeah, that's a lot for one question, but I'm just getting started with Mongoose and need to get some things cleared up.
I have a mobile application that builds a fairly large JSON object from a user doing data collection in the field. When the user submits this object via a POST, I need to do several things to it before saving it. One that I most confused about the proper way is making references to other schemas. I have a long Oracle RDBMS background, so I'm struggling to "cross over".
When a user submits the json object to me, it's not very smart in relation to the schemas. The document just has a "username" which is the combination of two fields in my user schema, user_id and agency_id. A data object is created by a USER, and USERs are members of AGENCY(ies) which have agency_ids. Agency ID is not _id, it's a number given to them by me, it's a simple increment that is remember-able by the user like a email address. So when I get the json object, I need to lookup the user by user_id and agency_id, then replace the crewMember key with a user key that is the _id of the user I just looked up, prior to sticking the json into the model to validate. Is that doable directly in getters/setters? Is that the proper way to make a reference? Will the schemas do the right thing magically? I know they don't know how to find a user, but once I have found a user record, how to add it to the crewSchema that [needs to be || is already a] subdocument of the document schema
My (simplified) schemas:
user.js
var userSchema = mongoose.Schema({
user_id: {type: String, required: true},
password: {type: String, required: true},
agency_id: {type: String, required: true},
first_name: {type: String, required: true},
last_name: {type: String, required: true},
address: String,
city: String,
....
});
Document Schema:
document.js:
var crewSchema = new Schema(
{
crewMember:{ type: ObjectId , ref: 'User' }, << want to reference user in userSchema
crewRole: String,
crewLevel: String
}
var docSchema = mongoose.Schema({
{
runid: { type: String, required: true },
status: { type: String, required: false },
version:Number,
agency_id:Number,
times: {
recd: Date,
insvc: Date
},
crew: [crewSchema], <<<here is my crewschema subdocument - there can be multiple crew per document
ref_trip_no: String,
unit_id: String,
ix_loc: {
....
});
And here is a JSON object I receive from the app:
{ doc_info: {
doc_id: "1234656abc",
"crew": [
{
"crewMember":"nmartinez@1000", << this is user_id + '@' + agency_id from userSchema
"crewRole": "operator",
"crewLevel": "op3"
},
{
"crewMember":"sobannon@1000",
"crewRole": "safety",
"crewLevel": "op2"
}
],
"address": "123 main st",
...
}