Is there a way to pass user Id to schema? - node.js

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

Related

How to 'join' or populate an array

Here is my very basic product schema:
const productSchema = new Schema({
productName: {
type: String,
required: true,
},
productDescription: {
type: String,
},
productPrice: {
type: Number,
},
});
module.exports = mongoose.model("Product", productSchema);
These products are listed out and a user can add a quantity for each. I am storing in an array of objects as per below. I want to join these two collections together so that I can output the qty of products selected by the user. I believe I need to use populate here but not sure how to set up the Refs and so on.
const PartySchema = new Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
catering: [{ id: mongoose.Types.ObjectId, qty: Number }],
created_at: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Party", PartySchema);
I'm sharing this solution with the assumption that the catering field is the sub-document array pointing to the Product Schema:
The Product Schema is fine so it stays the same (although to keep to convention I would advice naming your schema 'Products' instead of 'Product', Mongo Naming Covention):
const productSchema = new Schema({
productName: {
type: String,
required: true,
},
productDescription: {
type: String,
},
productPrice: {
type: Number,
},
});
module.exports = mongoose.model("Products", productSchema);
And next the Party Schema would be:
const PartySchema = new Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
catering: [{
id: {
type: mongoose.Types.ObjectId,
ref: 'Products',
},
qty: {
type: Number,
}
}],
created_at: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Parties", PartySchema);

Query multiple collections Nodejs

Hello im trying to join these collections i want to get all users which has "active" attribute equal to false. I couldn't figure out how to acquire this query. There are my schemas:
User Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
type: {
type: String,
required: true
},
active:{
type:Boolean
}
});
module.exports = mongoose.model('users', UserSchema);
Company Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CompanySchema = new Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
companies: [{
name: {
type:String
},
country:{
type:String
}
}
]
});
module.exports = Company = mongoose.model('company', CompanySchema);
Note: Not all users have companies only the type "client" and i want to get both, "client" and "employe"
You may want to refactor your Schema to better accommodate the type of data you have available.
For example:
User Schema:
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
type: {
type: String,
required: true
},
active:{
type:Boolean
},
companies: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'company'
}]
});
And Company Schema:
const CompanySchema = new Schema({
name: {
type:String
},
country:{
type:String
}
});
Then to get a list of all users who are active, and automatically populate any company data for those users (Assuming your user model is called UserModel)
UserModel.find({ active: false }).populate('companies').exec();
If you are unable to edit your data structure for any reason, then you could perform a query similar to:
CompanyModel.aggregate([
{ $lookup: { from: 'users', localField: 'userId', foreignField: '_id', as: 'user' } },
{ $match: { '$user.active': false } }
]).exec()
This will perform an aggregate lookup on the UserId field and then only match on ones where the active property is set to false.

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.

nested ref to populate mongoose 5.0 nodejs

I have two models. The first one is UserSchema and the second one is CategorySchema
var UserSchema = Schema({
firstName: {
type: String,
required: true
},
secondName: String,
lastName: {
type: String,
required: true
},
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
status: {
type: String,
required: true
},
roles: [{
type: Schema.ObjectId,
ref: 'Role'
}],
publications: [{
title: {
type: String,
},
description: String,
status: {
type: String,
},
createdAt: {
type: Date
},
updatedAt: {
type: Date,
default: Date.now()
},
pictures: [{
name: String
}],
categories: [{
type: Schema.Types.ObjectId,
ref: 'Category'
}],...
the model category is
var CategorySchema = Schema({
name: String,
subcategories: [{
name: String
}]
});
UserSchema has publications. Publications contains an array. Within of publications is categories that contains an array of id of subcategory(subcategory is whithin of CategorySchema)
the problem is when I need to populate categories of UserSchema. Categories of UserSchema have an array of _id of subcategory that belongs to CategorySchema.

mongoose index creation issue after drop collection

I had created one index on the collection and it was created. But after the drop that collection and when I restarted node server then collection are created again but the index isn't can anybody suggest what is the cause?
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const validator = require('validator')
const FeatureSchema = new Schema({
name:{
type: String,
trim: true,
required: "Please enter a feature name!"
},
slug: String,
description: {
type: String,
trim: true
},
author: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: 'You must supply an author'
},
productID: {
type: mongoose.Schema.ObjectId,
ref: 'Product',
required: 'You must supply an product'
}
},{
timestamps: {
createdAt: 'createdDate',
updatedAt: 'updatedDate'
}
});
// Define our indexes
FeatureSchema.index({
name: 'text'
});
module.exports = mongoose.model('Feature', FeatureSchema);
try to stop mongodb service and restart it again.

Resources