Reputation:
I have document like below. Here peoples
contains array of ObjectId which points to user collection. And contribution
field contains as many number of subdocument as peoples
field. Length is variable like if some group has 2 ObjectId in people
then contribution
will have 2 sub document. I need to create mongoDb schema for this, please tell me schema for this.
{
name: "person name",
_id: ObjectId(""),
creater: ObjectId("1"), //referencing to user collection
peoples: [ObjectId("1"), ObjectId("2"),...upto n], //all referencing to user table
contribution: {
ObjectId("1"):{
paid: 1200,
due: 1000,
prevDue: 200,
Advance: 0
},
ObjectId("2"):{
paid: 1200,
due: 1000,
prevDue: 200,
Advance: 0
},
//upto end of lists in peoples array
},
estimated: 30000,
collected: 15379,
left: 14721
}
Upvotes: 2
Views: 1318
Reputation: 1127
You just need to reference the nested schema in your main schema
. For eg:
let user = new Schema({
name: String
})
let schema = new Schema({
followers: [user]
})
In the followers
field of schema
, you just referenced the user
schema. Whenever this kind of reference is done, the types of nested schema
get injected into the reference point.
Upvotes: 3
Reputation: 7190
I got it what you want to do but you can't iteration a schema object like an 'n' no of series.
An object schema in MongoDB is like key-value pair in JSON Object, you can't iterate it like a loop. Instead, the approach to do that is, define two different schemas and assign one schema in an array to use it in another schema as a subschema.
Follow the below-mentioned code:
{
name: "person name",
_id: ObjectId(""),
creater: ObjectId[1],
peoples: [ObjectId[0], ObjectId[1],...upto n-1],
ObjectId: [
{
paid: 1200,
due: 1000,
prevDue: 200,
Advance: 0
},
{
paid: 1200,
due: 1000,
prevDue: 200,
Advance: 0
}
],
estimated: 30000,
collected: 15379,
left: 14721
}
Upvotes: 1
Reputation: 3125
Here is an implementation. Notice that I defined contribution
property as an array of peopleContributionSchema
. This makes the collection data easier to be accessed as you can loop for items in that array. The way you implemented is not flexible as ObjectId
is a property of contribution, so you would need to know before hand the number of people in the contribution.
var peopleContributionSchema = new Schema({
_id: Schema.Types.ObjectId,
paid: Number,
due: Number,
prevDue: Number,
advance: Number
});
var parentSchema = new Schema({
_id: Schema.Types.ObjectId, // not necessary to define. Mongoose will add by default
name: String,
creater: Schema.Types.ObjectId,
peoples: [Schema.Types.ObjectId],
contribution: [peopleContributionSchema],
estimated: Number,
collected: Number,
left: Number
});
Upvotes: 2