MongoDB Many to many relationship reference with extra fields - node.js

I have 2 models - User & Project.
Relations are -
Users can have multiple projects (One to many)
One projects may be shared with multiple other users. (Many to many)
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
mobile: {
type: Number,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
},
role: {
type: String,
default: 'basic',
enum: ["basic", "admin"]
},
projects: [
{
type: Schema.Types.ObjectId,
ref: 'Project'
}
],
shared_projects: [
{
type: Schema.Types.ObjectId,
ref: 'Project'
}
]
}, { timestamps: true });
const ProjectSchema = new Schema({
name: {
type: String,
required: true,
},
active: {
type: Boolean,
default: false,
},
expiry: {
type: Date,
default: null,
},
owner: {
type: Schema.Types.ObjectId,
ref: 'User'
},
shared_users: [
{
type: Schema.Types.ObjectId,
ref: 'User'
}
]
}, { timestamps: true });
I want to have a feature that the owner of the project may disable one or many shared user. So, I need a status field in ProjectSchema like -
shared_users: [
{
type: Schema.Types.ObjectId,
ref: 'User'
},
status: {
type: Boolean,
default: true
}
]
So, do I need to have the same definition in UserSchema also & update both schemas when user disable or enable a shared user?

Related

Trouble with mongoDB Ref -> trying to ref array of diferent model

so i'm trying ref a array of daysOff (Ferias model) as a fiel in a User model,
i'm new to MongoDB and mongoose, and i'm trying to build a API that manages a company workers days off.
I apologyse in advance for the "format" of this question but it's the very first time that I post a question in StackOverflow :)
Thanks u all!
const mongoose = require("mongoose");
const moment = require("moment");
const feriasSchema = mongoose.Schema(
{
user: {
type: mongoose.Types.ObjectId,
required: true,
ref: "User",
},
firstName: {
type: String,
ref: "User",
},
lastName: {
type: String,
ref: "User",
},
workerNumber: {
type: Number,
ref: "User",
},
sectionOfWork: {
type: String,
ref: "User",
},
totalFerias: {
type: Number,
required: true,
},
//this is the field i want to add in User model as an array of (dates format DD/MM/YYYY)
ferias: {
type: [String],
//default: [Date],
required: true,
},
tipoFerias: {
type: String,
required: true,
},
modo: {
type: String,
required: true,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("Ferias", feriasSchema);
// USER MODEL
const userSchema = mongoose.Schema(
{
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
email: {
type: String,
required: [true, "Please enter a valid email address"],
unique: true,
},
password: {
type: String,
required: [true, "Please enter a password"],
},
workerNumber: {
type: Number,
required: true,
unique: true,
},
sectionOfWork: {
type: String,
required: true,
},
chefia: {
type: String,
required: true,
},
//this is the field i want to be an array (from Ferias model)
ferias: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Ferias",
}],
role: {
type: String,
required: true,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", userSchema);
what am i doing wrong?
i'm getting and empty array ...
in express I can send the questioned data separately but u want to send a json to some frontend with all the fields of a user, with the "ferias" array present.

Mongoose/MongoDB Empty SubSchema Array

I have a model in Mongoose that looks like this:
const orderLogSchema = mongoose.Schema(
{
removed: { type: String, required: true },
},
{
timestamps: true,
}
)
const orderSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
orderItems: [
{
name: { type: String, required: true},
qty: { type: Number, required: true},
image: { type: String, required: true},
price: { type: Number, required: true},
product: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Product'},
}
],
shippingAddress: {
address: { type: String, required: true },
city: { type: String, required: true },
postalCode: { type: String, required: true },
country: { type: String, required: true },
},
paymentMethod: {
type: String,
required: true,
},
paymentResult: {
id: { type: String },
status: { type: String },
update_time: { type: String },
email_address: { type: String },
},
taxPrice: {
type: Number,
required: true,
default: 0.0
},
shippingPrice: {
type: Number,
required: true,
default: 0.0
},
totalPrice: {
type: Number,
required: true,
default: 0.0
},
isPaid: {
type: Boolean,
required: true,
default: false
},
paidAt: {
type: Date,
},
isDelivered: {
type: Boolean,
required: true,
default: false
},
deliveredAt: {
type: Date,
},
couponCode: {
type: Object,
required: false
},
orderVerifyLog: [orderLogSchema],
}, {
timestamps: true
})
I need to be able to empty out the orderVerifyLog which is populated with the orderLogSchema. I have tried a bunch of things most recently I pulled the order into a variable, and I am able to access orderVerifyLog by using order.orderVerifyLog but I cant figure out how to empty out that orderLogSchema. I tried:
order.orderVerifyLog = []
order.save()
Is there an easy way to work with that "sub" schema and zero it out?
Basically I am pulling the log items from that schema for an order and displaying them on my front-end. Then I was to fire off an action to clears it out so they don't display every time the order is loaded (Only want them to show once). I also tired to loop over each item in the orderVerifyLog and use pull to remove them, but for some reason it always leaves one in there.

Building Mongoose models for an Express Nodejs API with refpath

I'm new to building rest api's with mongoose and express and have a question on how to use refPath correctly on my Models files and allowing for an array of items.
Below I have included the code for a model (built thus far) and would love any input on if I'm even close to building this correctly.
I will also include a screenshot that visually depicts the relationships I'm trying to create.
Those who answer questions here are GODS and I appreciate all the help this community has given me over the years!
const mongoose = require("mongoose");
const slugify = require("slugify");
const AlertSchema = new mongoose.Schema({
parentId: {
type: mongoose.Schema.ObjectId,
required: true,
refPath: "parentModel",
},
parentModel: {
type: String,
required: true,
enum: ["orgs", "clients"],
},
status: { type: String, default: "no-status" },
departments: [{ type: mongoose.Schema.Types.ObjectId, ref: "orgs" }],
createdAt: { type: Date, default: Date.now },
createdByType: [{ type: mongoose.Schema.Types.ObjectId, ref: "users" }],
createdById: [{ type: mongoose.Schema.Types.ObjectId, ref: "users" }],
groups: [{ type: String, default: "unGrouped" }],
stage: [{ type: mongoose.Schema.Types.ObjectId, ref: "stages" }],
children: { type: String },
resource: {
type: String,
match: [
/https?:\/\/(www\.)?[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()#:%_\+.~#?&//=]*)/,
"Please use a valid URL with HTTP or HTTPS",
],
},
notes: [{ type: mongoose.Schema.Types.ObjectId, ref: "notes" }],
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: "comments" }],
priority: { type: String },
assignedTo: [{ type: mongoose.Schema.Types.ObjectId, ref: "users" }],
title: {
type: String,
required: [true, "Please add a title"],
maxlength: [50, "Title cannot be more than 50 characters"],
},
message: {
type: String,
required: [true, "Please add a message"],
maxlength: [500, "Message cannot be more than 500 characters"],
},
slug: String,
});
//create alert slug from the title
AlertSchema.pre("save", function (next) {
console.log("Slugify Ran", this.name);
this.slug = slugify(this.title, { lower: true });
next();
});
module.exports = mongoose.model("Testalert", AlertSchema);
Desired relationships diagram:

How to handle normalization on mongoDB collections?

There are two collections Employee and 'Project', It need to maintain history of project allocations for employee as well as projects basis.
I have created collection schema but it duplicates the data, is there any other way I can achieve this?
Employee Schema
const employeeSchema = mongoose.Schema({
name: {
type: String,
required: true
},
project: {
start: {
type: Date,
required: true
},
end: {
type: Date,
required: true
},
project: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Project',
required: true
}
},
}
Project Schema
const projectSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
employee: {
start: {
type: Date,
required: true
},
end: {
type: Date,
required: true
},
project: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Employee'
}
}
});
Or Can I create separate collection for mapping both project and employee? if I do this then what is the difference between MongoDB and RDBMS?

Mongoose Complex Query by Subdocument

I need to find a Project by either Owner, Manager, or one of the Team Members. Here's how the schema looks like:
var project = new mongoose.Schema({
title: { type: String, require: true },
slug: { type: String, require: true },
description: { type: String, require: true },
descriptionHtml: { type: String, require: true },
nextVanityId: { type: Number, default: 1 },
owner: { type: ObjectId, ref: 'Member', require: true },
teams: [{ type: ObjectId, ref: 'Team' }],
managers: [{ type: ObjectId, ref: 'Member' }]
};
var team = new mongoose.Schema({
name: { type: String, require: true },
slug: { type: String, require: true },
project: { type: ObjectId, require: true, ref: 'Project' },
created: { type: Date, require: true, default: Date.now },
members: [{ type: ObjectId, default: null, ref: 'Member' }]
};
My query method looks like this:
function findByMember (member, done) {
var id = member._id;
Project
.find()
.or([
{ owner: id },
{ managers: id },
{ 'teams.members': id }
])
.exec(done);
}
Currently it works for both owners and managers, but I'm drawing blanks when querying the members collection of each team. What should I use?
In order for your query to work you can approach the problem in 2 ways.
Solution 1
Have your teams as an embedded document in projects:
var team = new mongoose.Schema({
name: { type: String, require: true },
slug: { type: String, require: true },
project: { type: ObjectId, require: true, ref: 'Project' },
created: { type: Date, require: true, default: Date.now },
members: [{ type: ObjectId, default: null, ref: 'Member' }]
};
var project = new mongoose.Schema({
title: { type: String, require: true },
slug: { type: String, require: true },
description: { type: String, require: true },
descriptionHtml: { type: String, require: true },
nextVanityId: { type: Number, default: 1 },
owner: { type: ObjectId, ref: 'Member', require: true },
teams: [team],
managers: [{ type: ObjectId, ref: 'Member' }]
};
This way your project document will have the team information and the teams.members makes sense.
Solution 2
Denormalise your Team data to have only the relevant information embedded:
var team = new mongoose.Schema({
name: { type: String, require: true },
slug: { type: String, require: true },
project: { type: ObjectId, require: true, ref: 'Project' },
created: { type: Date, require: true, default: Date.now },
members: [{ type: ObjectId, default: null, ref: 'Member' }]
};
var project = new mongoose.Schema({
title: { type: String, require: true },
slug: { type: String, require: true },
description: { type: String, require: true },
descriptionHtml: { type: String, require: true },
nextVanityId: { type: Number, default: 1 },
owner: { type: ObjectId, ref: 'Member', require: true },
teams: [{
_id: { type: ObjectId, ref: 'Team' },
members: [{ type: ObjectId, default: null, ref: 'Member' }]
}],
managers: [{ type: ObjectId, ref: 'Member' }]
};
In this second approach you need to keep the Team document and the denormalised data in sync.

Resources