how to insert data into this Mongoose schema - node.js

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

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);
}

Could not find path in schema while using arrayfilters in mongoose

This is my shema in mongoose
import {Schema, model} from 'mongoose'
const EmployeeSchema = new Schema({
employeeCode: {
type: String,
},
name: {
type: String,
},
appraisal: {
status: {
type: String,
enum: ["not started", "in progress", "completed", "not started", "self rating"],
default: "not started"
},
objective_group: [{
name: {
type: Schema.Types.ObjectId,
ref: "ObjectiveGroup",
required: true
},
value: {
type: Number,
},
objective_type: [{
name: {
type: Schema.Types.ObjectId,
ref: "ObjectiveType",
required: true
},
value: {
type: Number,
},
objective_description: [{
name: {
type: Schema.Types.ObjectId,
ref: "ObjectiveDescription",
required: true
},
value: {
type: Number,
},
ratings: {
type: {
type: Schema.Types.ObjectId,
ref: "Ratings",
}
},
}],
training_recommendation: {
type: Schema.Types.ObjectId,
ref: 'TrainingRecommendation'
},
other_recommendation: {
type: Schema.Types.ObjectId,
ref: 'OtherRecommendation'
},
}],
}],
},
})
export default model('Employee', EmployeeSchema)
Here is my code for the following task
const updateValue = asyncHandler(async (req: Request, res: Response) => {
const {id, rating} = req.body
const employee = await Employee.findOneAndUpdate({
"_id": "6204935ebca89023952f2da9",
"appraisal.objective_group._id": "6207ec6a8bfc1226d3f36fb1"
},
{
$set: {
"appraisal.$[objective_group].value": 1234
}
},
{
arrayFilters: [
{
'objective_group._id': new mongoose.Types.ObjectId("6207ec6a8bfc1226d3f36fb1")
}
]
}
)
res.status(StatusCodes.OK).json({
employee
});
})
Here I am trying to update the value field in objective_group. To achieve this I am using arrayfilter. But I am getting this Error
Error: Could not find path "appraisal.0._id" in schema
When I am mongoose v6 it's showing this error. on mongoose v5 I am not getting any errors but the operation is not succeeding
There is the possibility that I am not using arrayfilters in the right way because inside objective_group I am storing objects inside the array.
I am new to StackOverflow so sorry for some mistakes
You just have a slight error with the path you're providing, the error means that the path you gave resolved into a none array value.
You just need to change your update part from:
"appraisal.$[objective_group].value": 1234
To:
"appraisal.objective_group.$[objective_group].value": 1234
Like so:
db.collection.update({
"_id": "6204935ebca89023952f2da9",
"appraisal.objective_group._id": ObjectId("6207ec6a8bfc1226d3f36fb1")
},
{
$set: {
"appraisal.objective_group.$[group].value": 1234
}
},
{
arrayFilters: [
{
"group._id": ObjectId("6207ec6a8bfc1226d3f36fb1")
}
]
})
Mongo Playground

How to populate the nested object id

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"
})

Mongoose won't populate an array or object

Im having an issue where i have a Fixtures schema like so:
const FixtureSchema = mongoose.Schema({
home: {
club: {
type: mongoose.Schema.Types.ObjectId,
ref: 'club'
},
score: {
type: Number,
default: 0
},
scorers: [
{
player: {
type: mongoose.Schema.Types.ObjectId,
ref: 'player'
}
}
]
},
away: {
club: {
type: mongoose.Schema.Types.ObjectId,
ref: 'club'
},
score: {
type: Number,
default: 0
},
scorers: [
{
player: {
type: mongoose.Schema.Types.ObjectId,
ref: 'player'
}
}
]
},
match_num: {
type: Number,
required: true
},
date: {
type: Date,
default: Date.now()
}
});
module.exports = Fixture = mongoose.model('fixture', FixtureSchema);
Club schema:
const ClubSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
module.exports = Club = mongoose.model('club', ClubSchema);
Player Schema:
const PlayerSchema = new mongoose.Schema({
name: {
type: String,
require: true
},
club: {
type: mongoose.Schema.Types.ObjectId,
ref: 'club'
},
stats: {
starts: {
type: Number,
default: 0
},
goals: {
type: Number,
default: 0
},
assists: {
type: Number,
default: 0
},
goal_streak: {
type: Number,
default: 0
}
}
});
module.exports = Player = mongoose.model('player', PlayerSchema);
I make a request like this:
router.get('/', async (req, res) => {
try {
const fixture = await Fixture.find()
.populate('player', ['name'])
.populate('club', ['name']);
res.json(fixture);
} catch (err) {
console.error(err.message);
}
});
Postman get request gives me:
[
{
"home": {
"score": 1,
"club": "5e3dfcffb52ec61c30fc44cd",
"scorers": [
{
"_id": "5e4aac5d81d92b368398bd4d",
"player": "5e3dfddd4884f51cb7ee61e9"
}
]
},
"away": {
"score": 0,
"club": "5e3dfd18b52ec61c30fc44ce",
"scorers": []
},
"date": "2020-02-17T15:07:57.229Z",
"_id": "5e4aac5d81d92b368398bd4c",
"match_num": 1,
"__v": 0
}
]
Why is it not populating the name of the player or the club??? It works when it is not stored in an array or object.. Ive tried looking for advice on other topics but cant find anything relating to this..
Thanks for any replies and advice
Turns out it was the same as the other questions!!! lol..
If i change :
.populate('club', ['name']);
to
.populate('home.club', ['name']);
and so on
it solves it...

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