On mongoDB using mongoose you can use two type of Schema for nested Schema.
- One is Embedded Schema.
- Another is Reference Schema.
Embeded scema
Embeded scema looks something like this .
var commentSchema = new mongoose.schema({
Commentor: id,
Comment: string
})
var imageSchema = new mongoose.schema(
{
Imageurl: string,
Likes: number,
Comments: [comment]
})
var userprofileSchema = new mongoose.schema({
username: string,
Images: [image]
})
mongoose.model(“image” , imageSchema);
mongoose.model(“comment”, commentSchema);
mongoose.model(“user”, userprofileSchema);
Now to query this you can simply do
var usercollection=mongoose.model(“user”)
usercollection.find(function(err,users){…..})
Reference Schema
Now as alternately you can use reference schema . For that you have to give the reference model name on the parent document .
So it will be like this way
var commentSchema = new mongoose.schema(
{
Commentor: { type: mongoose.Schema.ObjectId, ref: "user" },
Comment: string
}
)
var imageSchema = new mongoose.schema(
{
Imageurl: string,
Likes: number,
Comments: [{ type: mongoose.Schema.ObjectId, ref: "comment" }]
}
)
var userprofileSchema = new mongoose.schema(
{
username: string,
Images: [{ type: mongoose.Schema.ObjectId, ref: "image" }]
}
)
mongoose.model("image", imageSchema)
mongoose.model("comment", commentSchema)
mongoose.model("user", userprofileSchema)
Now to query this you have to populate the nested Shcema.
var usercollection=mongoose.model("user");
usercollection.find()
.populate("images")
.populate({
path:"images",
populate:{
path:"comments",populate:"commentor"
}
})
.exec(function(err,users){….}).