I'm trying to build a new instance with OneToOne association, according to https://www.npmjs.com/package/sequelize-typescript
models/measure.ts :
#Table({ tableName: "measure" })
export class Measure extends Model {
...
// Token
#ForeignKey(() => Token)
#Column({ type: DataType.INTEGER, allowNull: false, unique: true })
id_token!: number
#BelongsTo(() => Token)
token!: Token
}
models/token.ts :
#Table({ tableName: "token" })
export class Token extends Model {
...
// Measure
#HasOne(() => Measure)
measure: Measure
}
my sequelize instance :
export const sequelize: Sequelize = new Sequelize({
...
repositoryMode: true,
})
sequelize.addModels([Token, Measure])
export const tokenRepository = sequelize.getRepository(Token)
export const measureRepository = sequelize.getRepository(Measure)
now i want to create a new Measure instance, with an existing Token :
const token = await tokenRepository.findOne({where: {value: value}})
...
console.log(token.isNewRecord) // false
const measure = measureRepository.build({...params, token: token}, {include: [{model: tokenRepository}]})
console.log(measure.token.isNewRecord) // true
await measure.save() // it try to insert an new token here
Sequelize try to insert a new token instead of insert only the measure. Where is my mistake ?
I faced this issue some times ago and by reading the docs and trying few things on my side I conclude it was not possible.
From what I saw you can create a new object and all is nested objects in one time. But you can't create a new object and link it to other existing objects in one time.
To do so you will have to do yourself the necessary find and/or update.
I never managed to make it work in one step and the documentation never talk about this. Always says that all elements are new.
An instance can be created with nested association in one step, provided all elements are new.
For more details :
https://sequelize.org/master/manual/creating-with-associations.html
Project details
using NestJs framework with Sequelize library for ORM and Postgres as a database
Code details
i have a pipe class that acts like a validator for the uniqueness of the phone number in the request body where it tries to fetch the user's record corresponding to the supplied phone number
like this instruction:
constructor(
#InjectModel(User)
private readonly userModel: typeof User
) {}
const user = await this.userModel.findOne({
where: { phone }
});
Problem
i get this error in the console when executing the validator:
[ExceptionsHandler] Invalid value { phone: '+somePhoneNumber' }
sequelize library has one example of using findOne() method and it's as noted in the question here.
Edited
here is the phone attribute in user model:
#Column({
type: DataType.STRING,
unique: true,
allowNull: false
})
phone: string;
the object passed to where clause is actually an object of the shape {phone: '+somePhoneNumber'} which is invalid, it should be
const user = await this.userModel.findOne({
where: { phone: data.phone }
});
data is the data passed to the pipe transform function, in my case & for nestjs developer it's the DTO of the current endppoint.
I'm developing a RESTful API with Node.js, Mongoose and Koa and I'm a bit stuck on what are the best practices when it comes to schemas and input validation.
Currently I have both a Mongoose and Joi schema for each resource. The Mongoose schema only includes the basic info about the specific resource. Example:
const UserSchema = new mongoose.Schema({
email: {
type: String,
lowercase: true,
},
firstName: String,
lastName: String,
phone: String,
city: String,
state: String,
country: String,
});
The Joi schema includes details about each property of the object:
{
email: Joi.string().email().required(),
firstName: Joi.string().min(2).max(50).required(),
lastName: Joi.string().min(2).max(50).required(),
phone: Joi.string().min(2).max(50).required(),
city: Joi.string().min(2).max(50).required(),
state: Joi.string().min(2).max(50).required(),
country: Joi.string().min(2).max(50).required(),
}
The Mongoose schema is used to create new instances of the given resource at endpoint handler level when writing to the database.
router.post('/', validate, routeHandler(async (ctx) => {
const userObj = new User(ctx.request.body);
const user = await userObj.save();
ctx.send(201, {
success: true,
user,
});
}));
The Joi schema is used in validation middleware to validate user input. I have 3 different Joi schemas for each resource, because the allowed input varies depending on the request method (POST, PUT, PATCH).
async function validate(ctx, next) {
const user = ctx.request.body;
const { method } = ctx.request;
const schema = schemas[method];
const { error } = Joi.validate(user, schema);
if (error) {
ctx.send(400, {
success: false,
error: 'Bad request',
message: error.details[0].message,
});
} else {
await next();
}
}
I am wondering if my current approach of using multiple Joi schemas on top of Mongoose is optimal, considering Mongoose also has built-int validation. If not, what would be some good practices to follow?
Thanks!
It is a common practice to implement a validation service even if you have mongoose schema. As you stated yourself it will return an validation error before any login is executed on the data. so, it will definitely save some time in that case.
Moreover, you get better validation control with joi. But, it highly depends upon your requirement also because it will increase the extra code you have to write which can be avoided without making much difference to the end result.
IMO, I don't think there's a definite answer to this question. Like what #omer said in the comment section above, Mongoose is powerful enough to stand its own ground.
But if your code's logic/operations after receiving input is pretty heavy and expensive, it won't hurt adding an extra protection in the API layer to prevent your heavy code from running.
Edit: I just found this good answer by a respectable person.
In legacy project we are migrating to typegoose.
Right now it has mongoose models and
I need to reference from typegoose to the old mongoose models.
An example mongoose model:
export interface User extends Mongoose.Document {
FirstName: string;
LastName: string;
}
const userSchema = new Mongoose.Schema({
FirstName: String,
LastName: String,
}, {strict: false, versionKey: false});
export default Mongoose.model<User>('users', userSchema);
Now I created a typegoose model:
import UserModel, {User} from "./user";
export class Branch extends Typegoose {
#prop({ref: UserModel})
owner?: Ref<User>;
#prop()
name: string;
}
export const BranchModel = new Branch().getModelForClass(Branch);
I don't know how to fetch the branches user.
I try to populate BranchModel.find({}).populate({path: "user"})
but I get the error Schema hasn't been registered for model \"model\".\nUse mongoose.model(name, schema)","stack":"MissingSchemaError: Schema hasn't been registered for model \"model\".\nUse mongoose.model(name, schema)
May be I'm late replying to this, but I think you have two separate instances of mongoose in your application. I'm hoping in your legacy application, you're explicitly creating a mongoose instance on startup and Typegoose uses its own mongoose instance that I think is implicitly created by Typegoose.
In your case, you have to supply the existing mongoose instance to the getModelForClass method in the second argument as below
export const BranchModel = new Branch().getModelForClass(Branch, {existingMongoose: legacyMongooseInstance});
That should use the same mongoose instance and the Typegoose generated Schema can "see" the "legacy" schema. Refer the documentation of Typegoose.
I am currently trying to add a static method to my mongoose schema but I can't find the reason why it doesn't work this way.
My model:
import * as bcrypt from 'bcryptjs';
import { Document, Schema, Model, model } from 'mongoose';
import { IUser } from '../interfaces/IUser';
export interface IUserModel extends IUser, Document {
comparePassword(password: string): boolean;
}
export const userSchema: Schema = new Schema({
email: { type: String, index: { unique: true }, required: true },
name: { type: String, index: { unique: true }, required: true },
password: { type: String, required: true }
});
userSchema.method('comparePassword', function (password: string): boolean {
if (bcrypt.compareSync(password, this.password)) return true;
return false;
});
userSchema.static('hashPassword', (password: string): string => {
return bcrypt.hashSync(password);
});
export const User: Model<IUserModel> = model<IUserModel>('User', userSchema);
export default User;
IUser:
export interface IUser {
email: string;
name: string;
password: string;
}
If I now try to call User.hashPassword(password) I am getting the following error [ts] Property 'hashPassword' does not exist on type 'Model<IUserModel>'.
I know that I didn't define the method anywhere but I don't really know where I could put it as I can't just put a static method into an interface.
I hope you can help my find the error, thanks in advance!
I was having the same problem as you, and then finally managed to resolve it after reading the documentation in the TS mongoose typings (which I didn't know about before, and I'm not sure how long the docs have been around), specifically this section.
As for your case, you'll want to follow a similar pattern to what you currently have, although you'll need to change a few things in both files.
IUser file
Rename IUser to IUserDocument. This is to separate your schema from your instance methods.
Import Document from mongoose.
Extend the interface from Document.
Model file
Rename all instances of IUser to IUserDocument, including the module path if you rename the file.
Rename only the definition of IUserModel to IUser.
Change what IUser extends from, from IUserDocument, Document to IUserDocument.
Create a new interface called IUserModel which extends from Model<IUser>.
Declare your static methods in IUserModel.
Change the User constant type from Model<IUserModel> to IUserModel, as IUserModel now extends Model<IUser>.
Change the type argument on your model call from <IUserModel> to <IUser, IUserModel>.
Here's what your model file would look like with those changes:
import * as bcrypt from 'bcryptjs';
import { Document, Schema, Model, model } from 'mongoose';
import { IUserDocument } from '../interfaces/IUserDocument';
export interface IUser extends IUserDocument {
comparePassword(password: string): boolean;
}
export interface IUserModel extends Model<IUser> {
hashPassword(password: string): string;
}
export const userSchema: Schema = new Schema({
email: { type: String, index: { unique: true }, required: true },
name: { type: String, index: { unique: true }, required: true },
password: { type: String, required: true }
});
userSchema.method('comparePassword', function (password: string): boolean {
if (bcrypt.compareSync(password, this.password)) return true;
return false;
});
userSchema.static('hashPassword', (password: string): string => {
return bcrypt.hashSync(password);
});
export const User: IUserModel = model<IUser, IUserModel>('User', userSchema);
export default User;
And your (newly renamed) ../interfaces/IUserDocument module would look like this:
import { Document } from 'mongoose';
export interface IUserDocument extends Document {
email: string;
name: string;
password: string;
}
I think you are having the same issue that I just struggled with. This issue is in your call. Several tutorials have you call the .comparePassword() method from the model like this.
User.comparePassword(candidate, cb...)
This doesn't work because the method is on the schema not on the model. The only way I was able to call the method was by finding this instance of the model using the standard mongoose/mongo query methods.
Here is relevant part of my passport middleware:
passport.use(
new LocalStrategy({
usernameField: 'email'
},
function (email: string, password: string, done: any) {
User.findOne({ email: email }, function (err: Error, user: IUserModel) {
if (err) throw err;
if (!user) return done(null, false, { msg: 'unknown User' });
user.schema.methods.comparePassword(password, user.password, function (error: Error, isMatch: boolean) {
if (error) throw error;
if (!isMatch) return done(null, false, { msg: 'Invalid password' });
else {
console.log('it was a match'); // lost my $HÏT when I saw it
return done(null, user);
}
})
})
})
);
So I used findOne({}) to get the document instance and then had to access the schema methods by digging into the schema properties on the document user.schema.methods.comparePassword
A couple of differences that I have noticed:
Mine is an instance method while yours is a static method. I'm confident that there is a similar method access strategy.
I found that I had to pass the hash to the comparePassword() function. perhaps this isn't necessary on statics, but I was unable to access this.password
For future readers:
Remember that we are dealing with two different Mongo/Mongoose concepts: a Model, and Documents.
Many Documents can be created from a single Model. The Model is the blueprint, the Document is the thing created according to the Model's instructions.
Each Document contains its own data. Each also carries their own individual instance methods which are tied to its own this and only operate on that one specific instance.
The Model can have 'static' methods which are not tied to a specific Document instance, but operate over the whole collection of Documents.
How this all relates to TypeScript:
Extend Document to define types for instance properties and .method functions.
Extend the Model (of a Document) to define types for .static functions.
The other answers here have decent code, so look at them and trace through the differences between how Documents are defined and how Models are defined.
And remember when you go to use these things in your code, the Model is used to create new Documents and to call static methods like User.findOne or your custom statics (like User.hashPassword is defined above).
And Documents are what you use to access the specific data from the object, or to call instance methods like this.save and custom instance methods like this.comparePassword defined above.
I cannot see your IUser interface however I suspect that you have not included the methods in there.
EG
export interface IUser {
email: string,
hash: string,
salt: string,
setPassword(password: string): void,
validPassword(password: string): boolean,
generateJwt(): string
}
typescript will then recognize your methods and stop complaining
So the one with 70 updates I also gave an upvote. But it is not a complete solution. He uses a trivial example based on the OP. However, more often than not when we use statics and methods in order to extend the functionality of the model, we want to reference the model itself. The problem with his solution is he using a callback function which means the value of this will not refer to the class context but rather a global.
The first step is to invoke the statics property rather than pass the property as an argument to the static function:
schema.statics.hashPassword
Now we cannot assign an arrow function to this member, for this inside the arrow function will still refer to the global object! We have to use function expression syntax in order to capture this in the context of the model:
schema.statics.hashPassword = async function(password: string): Promise<string> {
console.log('the number of users: ', await this.count({}));
...
}
Refer : https://mongoosejs.com/docs/typescript.html
Just create an interface before the schema which represents a document structure.
Add the interface type to the model.
Export the model.
Quoting below from mongoose docs:
import { Schema, model, connect } from 'mongoose';
// 1. Create an interface representing a document in MongoDB.
interface User {
name: string;
email: string;
avatar?: string;
}
// 2. Create a Schema corresponding to the document interface.
const schema = new Schema<User>({
name: { type: String, required: true },
email: { type: String, required: true },
avatar: String
});
// 3. Create a Model.
const UserModel = model<User>('User', schema);
If you add any method to the schema, add its definition in the interface as well.