Reference to an object that is inside an array of objects mongoose - node.js

I want to ref a slot by objectid which is inside an array of object in different schema,
Here is my DoctorSlots schema:
const DoctorSlots = new mongoose.Schema({
doctor: { type: mongoose.Schema.Types.ObjectId, ref: 'Doctors' ,required: true ,trim: true},
slots: [{
startTime: {type: Date, },
endTime: { type: Date },
status: {type: String, default: "active"
} //this is the object that i want to ref
}]
},{timestamps: true})
const slotSchema = mongoose.model('doctorslots',DoctorSlots)
this is appointment schema
const AppointmentSchema = new mongoose.Schema({
userDetails: {type: mongoose.Schema.Types.ObjectId, ref: 'User', required:true },
doctorDetails: { type: mongoose.Schema.Types.ObjectId,ref: 'Doctors' ,required: true },
appointTime: {
time: {
type: mongoose.Schema.Types.ObjectId, ref: ''
} //here i want to ref that slot objcet id inside that array
}
}, {timestamps: true})
const appointmentSchema = mongoose.model('appointments', AppointmentSchema)
I want to ref an object in time: field of appointment schema which will refer an object from slots(array of obj) of doctorslots schema. what should be inside " ref:'' "?

Related

How to populate a data for a field in mongoose, where reference is a nested array in model?

How can I populate category in courses model?
I have courses, courses will have category from categories->subcategories model.
I don't know how to populate from nested objects.
Reference model is category, I have to populate from array subcategories!
**courses:**
const CourseSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
name: {
type: String
},
description: {
type: String
},
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'category'
}
});
**category:**
const mongoose = require("mongoose");
const CategorySchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
name: {
type: String,
required: true
},
subcategories: [{
name: {
type: String
}
}]
});
const Category = mongoose.model('category', CategorySchema);
module.exports = Category;
use seprate collection for subCetagory like:
**courses**
const CourseSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
name: {
type: String
},
description: {
type: String
},
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'SubCategory'
}
});
**SubCategory:**
const mongoose = require("mongoose");
const SubCategorySchema = new mongoose.Schema({
name: {
type: String,
required: true
},
categorie: {
type: String,
ref: "category"
}
});
const SubCategory = mongoose.model('category', SubCategorySchema);
module.exports = SubCategory;
**Category**
const mongoose = require("mongoose");
const CategorySchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
name: {
type: String,
required: true
},
subcategories: [
{
type: Schema.types.objectId,
ref: "SubCategory"
}
]
});
then just add subcetagory id to course when insert new course or update a course and when you want to get course along with subcetagory and category use populate query of mongoose

Is there a way to pass user Id to schema?

I have a user schema and an exam schema, i wanted to pass the id of the user to the schema of the exam
const ExamSchema = new mongoose.Schema({
-----> _id: [{
class: { type: String, required: true },
module: { type: Number,required:true },
date: {type: Date, required: true }
}]
Where it says _id - i wanted it to be the id of the user! Should i do it like this or add the exams schema on the user schema? Like this?
const UserSchema = new mongoose.Schema({
username: { type: String, require: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
active: { type: Boolean, default: true },
exam: [{
class: { type: String, required: true },
module: { type: Number,required:true },
date: {type: Date, required: true }
}]
});
Check Mongoose "Populate"
https://mongoosejs.com/docs/populate.html
A part from the docs,
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
So far we've created two Models. Our Person model has its stories field set to an array of ObjectIds. The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _ids we store here must be document _ids from the Story model.
In your case just make a user_id in Exam Schema and refer to id of User Schema
const ExamSchema = new mongoose.Schema({
user_id: {type: Schema.Types.ObjectId, ref: 'User' },
class: { type: String, required: true },
module: { type: Number,required:true },
date: {type: Date, required: true }
})

How can Mongoose Populate not working with Array of ObjectIds?

I'm trying to populate a mongoose query with an array of objectId field.
In another field with single objectId ref is working fine.
That's my "User" model:
const User = new Schema({
nome: {
type: String,
required: true
},
email: {
type:String,
required: true
}
})
mongoose.model('users',User)
That's my "Pedido" model:
const Schema = mongoose.Schema
const Pedido = new Schema({
id: {
type: String,
required: true
},
cliente: {
type: Schema.Types.ObjectId,
ref: 'clientes',
required: true
},
fotografos: {
type: [Schema.Types.ObjectId],
ref: 'users'
}
})
mongoose.model('pedidos',Pedido)
my router:
router.get('/pedidos',async(req,res)=>{
var query = await Pedido.find().populate('fotografos').populate('cliente').lean().exec()
console.log(query)
res.render("admin/pedidos",{pedidos: query})
})
That's the result in the console.log:
[
{
_id: 5e8e3bd16c57021f682b8e81,
fotografos: [],
cliente: {
_id: 5e8ccceea8a28146d86f4cac,
nome: 'Neymar',
email: 'neymar#ney.com',
__v: 0
},
__v: 0
}
]
fotografos field (array) are returning empty.
clientes field returns populated.
Can anybody help me with this?
You can use this code...
fotografos:[{
type: [Schema.Types.ObjectId],
ref: 'users'
}]
**Then do Populate**

Using schema attributes within it's own schema? mongoose nodejs

is there a way that I could use a schema attribute within it's own model
var mongoose = require("mongoose");
//====================================================
// Schema
//====================================================
var bookSchema = new mongoose.Schema({
name: String,
image: String,
summary: String,
author: String,
genre: String,
publisher: String,
available: Number,
submitted: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User" //model name
},
username: String
},
reviews: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Review"
}
],
reserves: {
type: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Reserve"
}],
validate: [arrayLimit, '{PATH} exceeds the limit of 5']
}
});
function arrayLimit(val) {
return val.length <= 5;
}
module.exports = mongoose.model("Book", bookSchema);
in the function arraylimit. I'm trying to replace the "5" with the "available" attribute from the bookSchema.

Mongoose query compare ObjectId

I'm trying to fetch some documents from my db. In each document, there is a field called 'owner' which is an ObjectId of a user. I want to fetch all of the documents of a specific user. I have the user id and when I'm trying to do something like this:
exports.getBoxes = function(req, res) {
const { user } = res.locals;
const query = db.Box.find();
query.where('owner').equals(user._id);
query.exec(function(err, boxes) {
console.log(boxes);
});
}
I get an empty array. I saw in my db and there are many boxes that corresponds to this query. What's wrong with it?
UPDATE
Here is my schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const timestamps = require('mongoose-timestamps');
const BoxSchema = new Schema({
description: {
type: String,
trim: true
},
producer: {
type: String,
trim: true
},
cycle: {
type: String,
trim: true
},
owner: {
type: Schema.ObjectId,
ref: 'Supplier'
},
event: {
type: Schema.ObjectId,
ref: 'Event'
},
type: {
type: String,
enum: []
},
creditTerms: {
type: String,
enum: ['Cash', '30 Days', '60 Days', '90 Days', '120 Days']
},
bids: [{
type: Schema.ObjectId,
ref: 'Bid'
}],
looking: [{
type: Schema.ObjectId,
ref: 'User'
}],
sold: Boolean,
paid: Boolean,
delivered: Boolean,
sealed: Boolean,
initialPrice: Number,
value: Number,
cts: Number,
ppc: Number,
finalPrice: Number
});
BoxSchema.plugin(timestamps);
module.exports = mongoose.model('Box', BoxSchema);
And here is an example of documents that I try to fetch:
https://i.gyazo.com/38f2d16d6831b831adb3cc448ef74d01.png
Okay guys I managed to solve this problem. The problem was that the owner field in the box schema referenced a Supplier object, not a User object. So I solved it like so:
const { user } = res.locals;
return db.Supplier.findOne({ userId: user._id })
.populate('boxes').exec(function(err, supplier) {
if(err || !supplier) return res.sendStatus(404);
res.json(supplier.boxes);
});

Resources