Hide all hidden mongoose methods and properties - javascript

I use nuxt 3. I have this code on my serverside.
findAuthorByEmail(email: string, showPassword = false) {
return Author.findOne({ email })
.select(showPassword ? "" : "-password_hash")
.lean();
},
Inside my /server/api/login.post.ts i return it here:
return {
token,
author,
};
Nuxt has the feature to provide the types for my front end. What should my query look like so that my response only provides the properties which are available? If I try to use for example $isDefault then it does not work of course.
Here is also my mongoose model:
import { Document } from "mongoose";
import { AuthorI } from "~~/types";
import { conn } from "../configuration/connection";
import { authorConfig } from "../configuration/author";
import mongoose from "mongoose";
const schema = new mongoose.Schema({
email: {
required: true,
type: String,
trim: true,
lowercase: true,
unique: true,
},
password_hash: {
type: String,
required: true,
trim: true,
minlength: authorConfig.password_min_length,
},
name: {
maxlength: authorConfig.name_length,
trim: true,
type: String,
},
family_name: {
type: String,
maxlength: authorConfig.family_name_length,
trim: true,
},
description: {
type: String,
maxlength: authorConfig.description_length,
trim: true,
},
props: {},
username: {
type: String,
trim: true,
unique: true,
required: true,
maxlength: authorConfig.username_length,
},
created: {
type: Date,
required: true,
default: Date.now,
immutable: true,
},
enabled: {
type: Boolean,
default: true,
},
});
export const Author = conn.model<AuthorModel>("Author", schema);
interface AuthorModel extends AuthorI, Document {}

use .lean() method. check official doc mongoose lean

Related

MongoDB Create New Document that references another Collection's Document IDs

I am trying to create a new document in the Form collection. This document references many FormSection documents. Here are the Schemas:
const FormSchema = new Schema({
title: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true,
unique: true
},
sections: [{
type: FormSectionDetails
}],
createdDate: {
type: String,
required: false,
unique: true
},
lastEdited: {
type: String,
required: false,
unique: true
}
});
const FormSectionDetails = new Schema({
section: {
type: Schema.Types.ObjectId,
ref: 'FormSection',
required: true
},
position: {
type: Number,
required: true
}
});
const FormSectionSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
display: {
type: String,
required: true,
},
category: {
type: String,
required: true
},
...
});
let FormSection;
try {
FormSection = mongoose.connection.model('FormSection');
} catch (e) {
FormSection = mongoose.model('FormSection', FormSectionSchema);
}
However, when I try to add a new document to the Forms collection, I get an error:
Document being inserted:
formData = {
"title": "Returning Members",
"description": "Returning Members",
"sections":
[{
"section": "6292c0fbd4837faca1d85d4d",
"position": 1
},
{
"section": "6292c0fbd4837faca1d85d4e",
"position": 2
},
...
}
Code being run:
formdata.sections.map(s => {
return {
...s,
section: ObjectId(s.section),
}}
);
return await FormSection.create(formdata);
Error message:
ValidationError: category: Path `category` is required., display: Path `display` is required.````
Seems like it is trying to create a new FormSection document. I don't want it to create a new FormSection document. I just want it to reference existing FormSection documents using the Object IDs I specified.
The Issue seems to be with how you declare the section field in the FormSchema. Try this:
const FormSchema = new Schema({
title: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true,
unique: true
},
sections: [{
type: ObjectId,
ref: 'FormSectionDetails',
required: true,
}],
createdDate: {
type: String,
required: false,
unique: true
},
lastEdited: {
type: String,
required: false,
unique: true
}
});
This would just store the _ids of the existing FormSectionDetails
It turns out I was inserting the document into the wrong collection. Instead of the code snippet:
return await FormSection.create(formdata);
It should actually be:
return await Form.create(formdata);
The error message should have been a more obvious hint for me as to what the problem was.

use mongoose expires to remove a ref object id from document

i have 2 schema TokenSchema and DriverSchema :
const tokenSchema: Schema = new Schema({
token: { type: String, required: true },
creationDate: { type: Date, required: true, expires: '1m', default: Date.now },
});
const driverSchema: Schema = new Schema({
drivingLicenseNumber: {
type: Number,
required: true,
unique: true,
},
name: { type: String, required: true },
lastName: { type: String, required: true },
email: {
type: String,
required: true,
unique: true,
},
phone: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
token: {
type: Schema.Types.ObjectId,
ref: 'Token',
},
});
i need to remove the token id ref from the driver then i remove the token object is that possible ?

Node Populate Array with object reference

I need to Populate courses of StudentSchema with the courses (Object_id) from CoursesSchema that belong to the major same as students major
let StudentSchema = new Schema({
_id: new Schema.Types.ObjectId,
emplId: {
type: Number,
required: true
},
major:{
type: String,
required: true
},
courses:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'courses',
grade:{
type: String,
required: false,
}
}],
});
const courseSchema = new mongoose.Schema({
code: {
type: String,
required: true
},
title: {
type: String,
required: true
},
//array of majors that a courses is required for e.g: ['CS', 'CIS']
major: {
type: Array,
required: false,
},
//
CIS:{
type: Boolean,
required: false,
},
CNT:{
type: Boolean,
required: false,
},
CS:{
type: Boolean,
required: false,
},
GIS:{
type: Boolean,
required: false,
},
})
What do I do?
StudentCoursesRouter.get('/studentcourses', (req, res) => {
Courses.find({CS: true}, (err, courses) => {
if ( err ) {
console.log('Error occured while getting records');
res.json(err);
} else {
courseMap = {}
courses.forEach(function(course) {
courseMap[course._id] = course._id;
});
//res.send(courses);
Students.find({empleId: 12345678}).courses.push(courses);
}
res.json(Students);
})
This is what i am doing but it is not populating courses of student and gives an empty array for courses.
API Request Response Screenshot
You mention populate but you are not using populate?
e.g. Students.find({empleId: 12345678}).populate('course')
If you want it lean u also need to install mongoose-lean-virtuals
e.g. Students.find({empleId: 12345678}).populate('course').lean({ virtuals: true })

How to make mongoose schema dynamic, depending upon the value?

I am new to mongoose and I have searched alot about it and was not able to find out the ans. Please help, thanks in advance.
const user = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true
},
rollno: {
type: Number,
required: true,
unique: true,
},
password : {
type: String,
required: true,
},
isVoter: {
type: Boolean,
required: true,
default: true
}
}, {
timestamps: true
});
Can I have a schema which would be dependent on the value of isVoter. For example if value of isVoter is false then we should have schema like this :
const user = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true
},
rollno: {
type: Number,
required: true,
unique: true,
},
password : {
type: String,
required: true,
},
isVoter: {
type: Boolean,
required: true,
default: true
},
promises: [
{
type: String
}
]
, {
timestamps: true
});
You can defined if one variable is required or not based in another property in this way:
promises: [
{
type: String,
required: function(){
return this.isVoter == false
}
}
]
So, promises will be required only if isVoter is false. Otherwise will not be required.
you can use pre hook in mongoose, check the documentation and before saving, check the isVoter value, if you don't want to save promises, try this.promises = undefined
user.pre('save', function(next) {
if(this.isVoter== true){
this.promises = undefined
}
else{
this.promises = "hello"
//do somethings
}
next();
});
and in the schema promises should be definded

How to sustainably organise user schema in mongoose

I have a user which should have the following fields and currently has following schema:
const UserSchema = new Schema(
{
email: {
type: String,
required: true,
index: { unique: true },
lowercase: true,
},
isVerified: { type: Boolean, default: false }, // whether user has confirmed his email
name: { type: String, required: false },
password: { type: String, required: true, minLength: 6 }, // object with next two included?
passwordResetExpires: Date,
passwordResetToken: String,
roles: [{ type: 'String' }], // Array of strings?
username: { type: String, required: false },
token: [{ type: String, required: false }], // used to send verification token via email
},
{ timestamps: true },
);
So yes, what is the world's default standard for organising user schemas. This schema's fields are pretty common, right?

Categories

Resources