I want to work in a sperate logic to Object in the code and DB object. The all idea is to isolate completly to real logic from DB stuff (for couple reason...one of them is if I would want to work with other DB in the future)
For now I am working with MongoDB, and I created some infractractures that can handle creation and write typescript object to DB and it is something like this:
import Address, { AddressSchema } from './addressDetails';
import { Document, Schema, model } from 'mongoose';
export default class User {
name: String;
address: Address;
constructor(params: { name: String, address: Address }) {
this.name = params.name;
this.address = params.address;
}
}
const UserSchema = new Schema({
name: String,
details: AddressSchema
});
export interface UserDocument extends User, Document { };
export const UserModel = model<UserDocument>('User', UserSchema);
now Address is a other object that look like this:
import { Document, Schema, model } from 'mongoose';
export default class Address {
country: String;
city: String;
streetAddress: String;
constructor(params: { country: String, city: String, streetAddress: String }) {
this.country = params.country;
this.city = params.city;
this.streetAddress = params.streetAddress;
}
}
export const AddressSchema = new Schema({
country: String,
city: String,
streetAddress: String
});
So actually Address is a nested schema inside User. So when I save UserModel it is look like this:
const newUser = new User(newUserParams);
const newUserModel = new UserModel(newUser);
newUserModel.save(......etc,etc
Inside the DB the User that we saved is looks like nested inforamation with ID for the Address section.
Now the things that I don't know is how do I read a document and parse is so I can create an new full instance of User main object.
By full I mean that it will create also instance of the nested Address inforamtion that comes from the document.
Thank you guys very much!
via bar zaruk
No comments:
Post a Comment