How to populate the nested object id - node.js

Here is my schema, I want to join the address in ScheduleSchema to addressDetails in CustomerSchema to list the all address details in a table, how to achieve this?
const CustomerSchema = new Schema(
{
addressDetails: [
{
block: {
type: String,
},
building_number: {
type: String,
},
is_default: {
type: Boolean,
default: false,
},
},
],
},
const SheduleSchema = new Schema(
{
customer: {
type: ObjectId,
required: true,
ref: "Customer",
},
address: {
type: ObjectId
},
week: {
type: String
}
},
schemaOptions
);

you must to use ref and populate for address key check the documnetation, and add this property to the Schemas like this :
const SheduleSchema = new Schema(
{
customer: {
type: ObjectId,
required: true,
ref: "Customer",
},
address: {
type: mongoose.Types.ObjectId,
ref: "Customer",
},
week: {
type: String
}
},
schemaOptions
);
use populate for get all addresses wit details
await SheduleSchema.find().populate({
path : "address"
})

Related

Reference to an object inside an array in another collection

Following is the WorkingDay model
const workingDaySchema = new mongoose.Schema({
date: { type: String, unique: true, required: true },
availableSlots: [
{
startTime: Date,
endTime: Date,
size: Number,
enrolledUsers: [{ type: Schema.Types.ObjectId, ref: 'Response' }]
}
]
})
module.exports = mongoose.model('WorkingDay', workingDaySchema);
And the following is the Response model:
const responseSchema = new Schema(
{
id: { type: String },
name: { type: String, required: true },
age: { type: String },
gender: { type: String },
height: { type: String },
weight: { type: String },
food: { type: String },
phone: { type: String },
email: { type: String },
category: { type: Array },
answers: { type: Object },
assignedSlot: { type: Schema.Types.ObjectId, ref: availableSlots, default: null }
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Response", responseSchema);
Every object inside the availableSlots array has it own unique _id.
How to create a reference to an object inside availableSlots from the assignedSlot field of response? Also how to populate the same?
I tried referencing the availableSlots objects using
assignedSlot: { type: Schema.Types.ObjectId, ref: availableSlots, default: null }
and
assignedSlot: { type: Schema.Types.ObjectId, ref: "WorkingDay.availableSlots", default: null }
but it did not work.
const { ObjectId } = mongoose.Schema.Types;
assignedSlot: [{ type: ObjectId ,ref:"WorkingDay"}]
Given your schema structure, you should reference the WorkingDay collection:
assignedSlot: { type: Schema.Types.ObjectId, ref: 'WorkingDay', default: null }
Then, you can populate the reference with:
const response = await Response.findOne({}).populate('assignedSlot').exec();
if (response && response.assignedSlot) {
console.log(response.assignedSlot.availableSlots);
}

how to insert data into this Mongoose schema

how to insert data in it on create method ? i have the following schema in which i want
to add data i am new and cannot understand that how to achieve this in mongoose please help i am having problrm when i insert the questions field remains empty instead of an array of objects
const { type } = require("express/lib/response");
const mongoose = require("mongoose");
const QuizSchema = mongoose.Schema({
course: {
type: mongoose.Schema.Types.ObjectId,
ref: "course"
},
topic: {
type: mongoose.Schema.Types.ObjectId,
ref: "topic"
},
quiztime: {
type: Date,
require: true,
},
allowedtime: {
type: Date,
require: true,
},
qusetions: [
{
questiontext: {
type: String,
},
correctans: {
type: String,
},
opt1val: {
type: String
},
opt2val: {
type: String
},
opt3val: {
type: String
},
opt4val: {
type: String
},
}
],
students: [
{
student: {
type: mongoose.Schema.Types.ObjectId,
ref: "student"
},
selectedans: [
{
anstext: {
type: String
}
}
]
}
],
},
{
timestamps: true,
});
const Quizmodel = mongoose.model("quiz", QuizSchema);
module.exports = Quizmodel;
and please also how to update if i want to

How to sort nested populated field in MongoDB (Mongoose)?

I am trying to sort populated array based on the nested and populated field using mongoose but it is not working.
Here are my modals.
const campaignSchema = new Schema(
{
name: { type: String, required: true },
prospects: [{ type: mongoose.Types.ObjectId, ref: "Prospect" }],
}
);
const prospectSchema = new Schema(
{
strategy: { type: String, trim: true },
contact: { type: mongoose.Types.ObjectId, ref: "Contact", required: true },
primaryCaller: { type: mongoose.Types.ObjectId, ref: "Contact" },
}
);
const contactSchema = new Schema(
{
firstName: { type: String, required: true },
lastName: { type: String, required: true },
}
);
Now I am trying to populate prospects and contact in each prospect in and sort them by contact.firstName using the following code.
const campaign = await Campaign.findOne({ _id: id }).populate({
path: "prospects",
populate: [
{ path: "contact", select: "firstName lastName" },
{ path: "primaryCaller", select: "firstName lastName" },
],
options: {
sort: "contact.firstName",
},
}).lean();
I tested it with sort: "strategy", and it is working fine with it.
I also tried Aggregations but it also didn't help.

update collection based upon other collection field

I have 2 schemas, this is parent collection schema:
const TimesheetSchema = Schema({
managersComment: {
type: String,
},
weekNum: {
type: Number,
},
year: {
type: Number,
},
user: { type: Schema.Types.ObjectId, ref: userModel },
status: {
type: String,
enum: ["Saved", "Submitted", "Approved", "Rejected"],
},
data: [{ type: Schema.Types.ObjectId, ref: TimesheetIndividualData }]
});
This is child collection schema
const TimesheetDataSchema = new Schema(
{
workingDate: {
type: Date,
},
dayVal: {
type: Number,
},
user: { type: Schema.Types.ObjectId, ref: userModel },
parentId: { type: String },
status: { type: String }
},
{ timestamps: true }
);
I want to update all status field in TimesheetDataSchema(child collection) based upon the parentId, here parentId is basically the _id of TimesheetSchema (parent collection).
Not sure how to do that through query in mongoose/mongo, so i am trying to do that through code in express.
Please help.
How about db.timeSheetData.updateMany({"parent_id": ObjectId(_id)}) ?
(Edit)
Fetch data from TimeSheetSchema collection.
Iterate through it and for each data get the _id.
db.timeSheetsData.updateMany({"parent_id": _id}, {"$set": {"status": data.status}

How can I fetch data from more than one collections in Mongo using mongoose

How I can display details data of a profile when those data stored in more than one collections
tried this link
const profile = await userKushala
.find({_id: '5cd407c741f9e7373f10362c'})
.populate({
path: 'settingId',
populate : {
path : 'specialty',
populate : {
path: 'hospital_attached'
}
}
})
// First Collection(Basic Info.)
const userRegisterSchema = new Schema({
userType: {
type: String,
required: true
},
mobile: {
type: Number,
required: true,
unique: true
},
userId: {
type: String,
required: true
},
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
gender: {
type: String,
required: true
},
settingId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'providerSetting'
}
})
// Second Collection(Detailed Info.)
const serviceProfileUpdate = new Schema({
specialty :[{
type: mongoose.Schema.Types.ObjectId,
ref: 'specialtyMasterCsv'
}],
category: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'categoryMasterCsv'
}],
subscriptionPlan: {
type: mongoose.Schema.Types.ObjectId,
ref: 'planMasterCsv'
},
medicine: {
type : mongoose.Schema.Types.ObjectId,
ref: 'kushalaUser'
}
})
//Data in Mongo
{
"_id":{
"$oid":"5cd93ea6bd96e43664f49bf3"
},
"specialty":[
{
"$oid":"5cda85f26ffe60259a75ba17"
},
{
"$oid":"5cda85f26ffe60259a75ba18"
}
],
"category":[
{
"$oid":"5cda85f26ffe60259a75ba17"
},
{
"$oid":"5cda85f26ffe60259a75ba18"
}
],
"subscriptionPlan":{
"$oid":"5cda85f26ffe60259a75ba17"
},
"medicine":{
"$oid":"5cd407c741f9e7373f10362c"
},
"__v":{
"$numberInt":"0"
}
}
Expected Result will be from all the collections data should fetch but with the code I have it's giving the result till specialty but after that it's printing only ObjectID
This is what I have done and it's working still if anyone has a better solution, most welcome. Hope it helps someone.
const profile = await userKushala
.find({_id: '5cd407c741f9e7373f10362c'})
.populate({
path: 'settingId',
populate : {
path : 'specialty category subscriptionPlan medicine'
}
})
Try to populate like this:
.populate([
{path:'category',model:'categoryMasterCsv'},
{path:'subscriptionPlan',model:'planMasterCsv'},
{path:'medicine',model:'kushalaUser'}])
This is the method I use daily.

Resources