how to create nested schema in nestjs use mongodb - mongodb

email
password
role
confirmed
id
address
city
street
My user schema should be like this. I want it to appear as a nested schema. separate the address space.
export const UserSchema = new mongoose.Schema({
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
role: { type: String, enum: Role, default: Role.USER },
confirmed: { type: Boolean, default: false },
id: { type: String, default: uuid.v4 },
});
UserSchema.pre('save', async function (next) {
try {
if (!this.isModified('password')) {
return next();
}
const hashed = await bcrypt.hash(this['password'], 10);
this['password'] = hashed;
return next();
} catch (err) {
return next(err);
}
});
interface user
export interface User extends Document {
id:string;
email: string;
password: string;
role: Role[];
address: ?
}
I have to add the address in user. How?
export const AddrSchema= new mongoose.Schema({
city: { type: String, default: "bb" },
street: { type: String, default: "aa" },
})

I think this will solve it.
export const UserSchema = new mongoose.Schema({
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
role: { type: String, enum: Role, default: Role.USER },
confirmed: { type: Boolean, default: false },
id: { type: String, default: uuid.v4 },
address: {
city: { type: String, default: "bb" },
street: { type: String, default: "aa" },
}
});

Related

Re: Correct MongoDb Relationships

Hi clever MongoDB people,
I am extremely new to Mongo DB and am trying to teach myself coding but I am battling with the practical side of collections.
I am attempting to create an employee management system and would like to know how do I get the different schemas/collections to only deal with the individual User’s employees.
A user will register using this schema;
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
lowercase: true,
},
companyName: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
role: {
type: String,
default: "customer",
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const User = mongoose.model("User", UserSchema:
);
module.exports = User;
Then the system takes them to a Profile page where they create a profile;
Profile Schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ProfileSchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
},
contactPerson: {
type: String,
required: true,
},
companyName: {
type: String,
required: true,
},
mobileNo: {
type: String,
required: true,
},
workNo: {
type: String,
},
email: {
type: String,
required: true,
},
industry: {
type: String,
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const Profile = mongoose.model("Profile", ProfileSchema);
module.exports = Profile;
Then they can add their employees.
Employee Schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const EmployeeSchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
},
employeeNo: {
type: String,
},
title: {
type: String,
},
employeeName: {
type: String,
required: true,
},
surname: {
type: String,
required: true,
},
gender: {
type: String,
},
race: {
type: String,
},
passportNo: {
type: String,
},
IDnumber: {
type: Number,
},
DOB: {
type: Date,
},
aka: {
type: String,
},
midName: {
type: String,
},
marriage: {
type: String,
},
passportExpires: {
type: Date,
},
mobileNo: {
type: String,
},
empEmail: {
type: String,
lowercase: true,
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const Employee = mongoose.model("Employee", EmployeeSchema);
module.exports = Employee;
Once an employee has been created there are various schemas connected with the employee, such as Personal contact details schema, Job details schema, Emergency contact details schema and so on.
This is my Emergency contact details schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const EmergencySchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
},
emergContactPerson: {
type: String,
required: true,
},
emergWorkNo: {
type: String,
},
emergMobileNo1: {
type: String,
required: true,
},
emergMobileNo2: {
type: String,
},
medicAidName: {
type: String,
},
medicPlan: {
type: String,
},
medicMemberNo: {
type: String,
},
medicDepCode: {
type: Number,
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const Emergency = mongoose.model("Emergency", EmergencySchema);
module.exports = Emergency;
My question is How do I create a one-to-many relationship between my schemas so that each User will only see their employees and their personal details?
Please can you help me?

How to define a proper mongoose schema?

Is this a proper way to define it?
const mongoose = require("../database");
// create a schema
var userschema =new mongoose.Schema({
name: String,
password: String,
email:String
});
var userModel=mongoose.model('users',userSchema);
module.exports = mongoose.model("Users", userModel);
//Please Try In This Way
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const User = mongoose.Schema(
{
name: {
type: String,
default: "",
trim: true,
},
email: {
type: String,
default: "",
trim: true,
validate: {
validator: async function (email) {
const user = await this.constructor.findOne({ email });
if (user) {
if (this.id === user.id) {
return true;
}
return false;
}
return true;
},
message: (props) => "This email is already in use",
},
required: [true, "User email required"],
},
password: {
type: String,
default: "",
trim: true,
select: false,
},
mobile: {
type: String,
default: "",
trim: true,
},
experience: {
type: String,
default: "",
trim: true,
},
agree: {
type: Array,
default: "",
trim: true,
},
status: {
type: Number,
default: 1,
},
type: {
type: String,
},
isDelete: {
type: Boolean,
default: false,
},
},
{
timestamps: { createdAt: "createdAt", updatedAt: "updatedAt" },
}
);
module.exports = mongoose.model("User", User);

Mongodb mongoose join two collection and fetch data

schema:
var UserSchema = new Schema({
id: { type: String, unique: true },
username: { type: String, unique: true },
password: String,
first_name: String,
last_name: String,
email: { type: String, unique: true },
phone: { type: String, unique: true },
status: { type: Boolean, default: false },
role: {
type: String,
enum: ["REGULAR", "ADMIN", "SUPER-ADMIN", "OPERATOR"],
default: "REGULAR",
},
tenantRef: { type: Schema.Types.String, ref: "tenant" },
teamRef: { type: Schema.Types.String, ref: "team" },
customerRef: { type: Schema.Types.String, ref: "customer" },
created: { type: Date, default: Date.now },
});
var CustomerSchema = new Schema({
id: { type: String, unique: true },
name: String,
plan: String,
billing: String,
status: { type: Boolean, default: true },
created: { type: Date, default: Date.now },
});
controller:
userController.getUsers = async function (req, res) {
const users = await UserSchema.find({}).populate({
path: "teamRef",
});
console.log(users);
return res.status(200).send(users);
};
Here i am trying to join user and customer so that i can get customer name along with user data .
I am using above way but it is not working.
Please take a look how can i do it

MongoDB (mongoose) about refs

who can explain with example how to get from another schema user data (for example useravatar)
while i read about refs and i cant understand.
This is my code, but i want to send back not only article but with profile datas about author. How can i do this ? I have authorID already for this.
router.post('/get-article', (req, res) => {
const { id, authorID } = req.body.data;
Article.findByIdAndUpdate({ _id: id }, { $inc: { "pageview": 1 } }, (err, article) => {
if (err) return res.status(400).json({ NotFound: "Article Not Found" })
res.json({ article })
})
})
article schema
const schema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: { type: String, required: true },
image: { type: String, required: true },
content: { type: String, required: true },
email: { type: String, required: true },
author: { type: String, required: true, index: true },
added: { type: Date, default: Date.now },
pageview: { type: Number, default: 0 }
});
User schema
const schema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
username: { type: String, required: true },
email: { type: String, required: true },
facebookId: { type: String },
githubId: { type: String },
googleId: { type: String },
useravatar: { type: String, required: true },
userip: { type: String, required: true },
accessToken: { type: String },
date: { type: Date, default: Date.now }
});

Sub-document validation receives array of documents

I have a Parent schema (Dashboard) that contains children (Widget).
The problem is that I need to validate single widget, but .pre('save') receives array of widgets.
Is there any way to validate single property? I tried to add widgetSize: { type: String, validate: xxx }, but with no luck.
var widgetSchema = new Schema({
_id: Schema.Types.ObjectId,
measurement: { type: String, required: true },
type: { type: String, required: true },
key: { type: String, default: '' },
background: { type: Schema.Types.Mixed, default: false },
localeId: { type: Schema.Types.Mixed, default: false },
hintText: String,
widgetSize: { type: String }
});
widgetSchema.pre('save', function (next) {
console.log(this);
if(!sizeValidator(this.widgetSize)) {
return next(new Error('Size format was incorrect: ' + this.widgetSize));
}
next();
});
var dashboardSchema = new Schema({
slug: { type: String, required: true },
name: { type: String, required: true },
backgroundImage: String,
defaultDashboard: { type: Boolean, default: false },
backgroundColor: String,
widgets: [widgetSchema]
});
The code to add a sub-documents
dashboard.widgets.push(widgetToCreate);
return dashboard.saveAsync(); // promisified
It looks like you were using this to validate the subdoc value which as you noticed is set to the top level document. More directly, you can use the value passed to the validate function like so:
var widgetSchema = new Schema({
_id: Schema.Types.ObjectId,
measurement: {
type: String,
required: true
},
type: {
type: String,
required: true
},
key: {
type: String,
default: ''
},
background: {
type: Schema.Types.Mixed,
default: false
},
localeId: {
type: Schema.Types.Mixed,
default: false
},
hintText: String,
widgetSize: {
type: String,
validate: function widgetSizeValidate(val) {
return val === 'foobar';
}
}
});