Monogo DB Schema - javascript

I needed a property of date/time which would allow to me get the time at which a certain task was created, I added timestamp property and set it to be true,
But I m not able to compile my code.
The code is perfectly running fine without the timestamp property
const mongoose = require("mongoose");
const Task = mongoose.model(
"Task",
({
title: {
type: String,
required: true,
trim: true,
},
description: {
type: String,
required: true,
trim: true,
minLength: 100,
},
completed: {
type: Boolean,
default: false,
},
},
{ timestamps: true })
);
module.exports = Task;
I needed a property of date/time which would allow to me get the time at which a certain task was created, I added timestamp property and set it to be true,
But I m not able to compile my code.

The mongoose.model() function of the mongoose module is used to create a collection of a particular database of MongoDB. The name of the collection created by the model function is always in plural format mean GFG to gfss and the created collection imposed a definite structure.
Syntax:
mongoose.model(<Collectionname>, <CollectionSchema>)
Parameters: This function accepts the following two parameters:
Collection name: It is the name of the collection.
Collection Schema: It is the schema of the collection.
Return type: This function returns the Mongoose object.
You need to pass a valid schema for the second argument like below
const mongoose = require("mongoose");
const TodoModel = mongoose.model(
"Task",
new mongoose.Schema(
{
title: {
type: String,
required: true,
trim: true,
},
description: {
type: String,
required: true,
trim: true,
minLength: 100,
},
completed: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
)
);
module.exports = TodoModel;
More about what is a valid schema refer below
https://mongoosejs.com/docs/schematypes.html

Related

How to skip the unique constraint validation on same document update

I have an update call as below in my NestJs project to update a mongoose model.
async updateRole(role_id: ObjectId, request: any): Promise<any> {
return this.roleModel.findByIdAndUpdate(role_id, {...request});
}
Here is the request I'm passing
{
"name":"Super-Admin",
"application": "62b2dbfd82045f40ea884334",
"active":true,
"privileges": ["62b2dbfd82045f40ea884334","62b2dbfd82045f40ea884334"],
"updated_by": "Abhilash.Shajan1#gmail.com"
}
Below is my role schema
import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
const RoleSchema = new Schema({
name: {
type: String,
required: true
},
application: {
type: Schema.Types.ObjectId,
ref: 'Application',
autopopulate: true,
required: true
},
active: {
type: Boolean,
required: true
},
privileges: [{
type: Schema.Types.ObjectId,
ref: 'Privilege',
autopopulate: true
}],
created_by: {
type: String
},
created_at: {
type: Date
},
updated_by: {
type: String
},
updated_at: {
type: Date
}
});
RoleSchema.index( { name: 1, application: 1 }, { unique: true } );
export { RoleSchema };
I already created a document (This is the only document now present in the roles collection) with the above request. Now I'm trying to update its active field to true.
Since i have unique compound index in the schema, it does not allow me to update the active field, I'm getting unique contraint error on both application and name field.
This error will be meaningful if i have another document with same name and application in the collection, but there is not.
Another way is to pass the active field alone in the request. But it will not help in my case because the UI is always passing the whole fields which include the unchanged values as well.
Any suggestions ?

Mongodb - mongoose autoincrement custom ID JS

I'm working on a membership admin pannel and I'm required to do a custom membership ID asides from the _id itself.
My schema is actually looking like this:
const mongoose = require("mongoose");
const memberSchema = mongoose.Schema(
{
membershipId: {
/* AutoIncrement custom id */
type: Number,
default: 1,
unique: true,
index: true,
autoIncrement: true,
},
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
},
{
timestamps: true,
}
);
const Member = mongoose.model("Member", memberSchema);
module.exports = Member;
the point is that I would like to have something standarized by the company, such as... EMP-00001, EMP-000002, that autoincrements.
Is it possible? If so, how can I achieve this?
Thank you in advance.

Student, teacher one common model or two separate ones in mongoose?

I need to create an account for a student and a teacher. Should I create two separate models in mongoose for student and teacher? What's the right approach? Student and teacher will share some properties and some will differ.
At this moment I have only one model for student and tutor:
const userSchema = new Schema({
name: {
type: String,
trim: true,
required: true,
maxLength: 32
},
surname: {
type: String,
trim: true,
required: true,
maxLength: 32
},
email: {
type: String,
unique: true,
trim: true,
required: true,
lowercase: true
},
isActiveTutor: {
type: Boolean,
default: false
},
birthCountry: String,
initials: String,
hashed_password: {
type: String,
required: true
},
salt: String,
role: {
type: String
},
teachingLanguage:{
type: Object,
/*language: {
language,
level,
price
}*/
},
resetPasswordLink: {
data: String,
default: ''
}
}, {timestamps: true});
But what if I wanted to give a teacher properties that a student would not have?
In case someone pass by here.
const options = {discriminatorKey: 'kind'};
const userSchema = new mongoose.Schema({/* user schema: (Common) */}, options);
const User = mongoose.model('User', userSchema);
// Schema that inherits from User
const Teacher = User.discriminator('Teacher',
new mongoose.Schema({/* Schema specific to teacher */}, options));
const Student = User.discriminator('Student',
new mongoose.Schema({/* Schema specific to student */}, options));
const teacher = new Teacher({/* */});
const student = new Student({/* */});
Original answer(modified): here.
Have a look at the docs here.

Object inside a field of mongoose Schema

I am building an API that gives info about laptops. I am using node and mongoDB with mongoose for this. This is my Schema -
const productSchema = mongoose.Schema(
{
name: {
type: String,
required: [true, 'A product must have a name'],
unique: true,
},
},
{
toJSON: {
virtuals: true,
},
toObject: {
virtuals: true,
},
});
I have a name field. I also want a "specs" field that should be an object. I want define rules for the properties in the object of the "specs" field. What I expect to come in the specs field is -
specs: {
memory: "16gb",
storage: "512gb",
"processor": "i7 2.2ghz"
}
So, I want to define rules for 'memory', 'storage', 'processor' in the 'specs' object
If by rules you mean a schema object rules, then possibly something like this would do:
specs: {
memory: {
type: String,
default: null
},
storage: {
type: String,
default: null
},
processor: {
type: String,
default: null
}
}
You can add more rules as you need.

How can I define a field with a range of data in mongoose schema?

My current Mongoose Schema is this:
const mongoose = require('mongoose');
const resultSchema = new mongoose.Schema({
scores: { type: Number, required: true },
analysis: { type: String, required: true }
},
{ timestamps: true, toJSON: { virtuals: true } }
);
module.exports = mongoose.model('Result', resultSchema);
And I want that scores field has a range of numbers. For example 100 to 500.
What should I do?
Meanwhile, Can I use MongoDB operator in Mongoose?
Mongoose has several built-in validators to satisfy exactly this use case.
Since scores is of type Number, you can use the min and max validators to validate a range in this manner:
const mongoose = require('mongoose');
const resultSchema = new mongoose.Schema({
scores: {
type: Number,
required: true,
min: 100,
max: 500
},
analysis: {
type: String,
required: true
}
}, { timestamps: true, toJSON: { virtuals: true } });
module.exports = mongoose.model('Result', resultSchema);
You can read about validation in Mongoose: https://mongoosejs.com/docs/validation.html

Categories