Go, Mongo problems - mongodb

I am new using Go, but I would like to know if there is a problem if I add new attributes to a Collection in Mongo, once my model is defined in Go. Form example
I defined in Go this Model:
type material struct {
ID string `bson:"_id" json:"_id"`
Name string `bson:"name" json:"name"`
Entity string `bson:"entity" json:"entity"`
}
and I create new attributes on Material Collection for example:
Collection Material
All Attributes: ID, Name, Entity,Country(NEW ONE)
Is it necessary to update the model knowing that I will not use that attribute for the project?

Related

GORM foreign key doesn't seem to add proper fields

I have the following model:
type Drink struct {
gorm.Model // Adds some metadata fields to the table
ID uuid.UUID `gorm:"type:uuid;primary key"`
Name string `gorm:"index;not null;"`
Volume float64 `gorm:"not null;type:decimal(10,2)"`
ABV float64 `gorm:"not null;type:decimal(10,2);"`
Price float64 `gorm:"not null;type:decimal(10,2);"`
Location Location `gorm:"ForeignKey:DrinkID;"`
}
type Location struct {
gorm.Model // Adds some metadata fields to the table
ID uuid.UUID `gorm:"primary key;type:uuid"`
DrinkID uuid.UUID
Name string `gorm:"not null;"`
Address string `gorm:"not null;type:decimal(10,2)"`
Phone int `gorm:"not null;type:decimal(10,0);"`
}
however, when I run the program, it adds both tables, however there is no location field in the Drink table.
My database looks like this after the migrations, regardless of whether I drop the tables previously:
I have a sneaking feeling it might be because I am not using the gorm default ID, but if that's the case can anyone point me to how to override the default ID with a UUID instead of a uint the proper way? or if that's not even the issue, please, I've been working on this for a few days now and I really don't want to take the "easy" road of just using the defaults gorm provides, I actually want to understand what is going on here and how to properly do what I am trying to do. I am getting no errors when running the API, and the migration appears to run as well, it's just the fields I have defined are not actually showing up in the database, which means that the frontend won't be able to add data properly.
What I WANT to happen here is that a list of stores will be available in the front-end, and when a user adds a drink, they will have to select from that list of stores. Each drink added should only have 1 store, as the drinks prices at different stores would be different. So technically there would be many "repeated" drinks in the drink table, but connected to different Locations.
First point is as you are using custom primary key, you should not use gorm.Model as it contains ID field in it. Reference
Second point is according to your description, store (location) has one to
many relationship with drink. That means a store can have multiple
drinks but a drink should belong to only one store. In one-to-many
relationship there should be a reference or relation id in the many
side. That means in your case in drink table. Then your struct
should look like this:
MyModel Struct
type MyModel struct {
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
Location Struct (Store)
type Location struct {
MyModel
ID uuid.UUID `gorm:"primary key;type:uuid"`
// other columns...
Drinks []Drink
}
Drink Struct
type Drink struct {
MyModel
ID uuid.UUID `gorm:"type:uuid;primary key"`
//other columns...
LocationID uuid.UUID// This is important
}
Then gorm will automatically consider LocationID in drink table will be referring the ID field of Location Table. You can also explicitly instruct this to gorm using gorm:"foreignKey:LocationID;references:ID" in Location struct's Drinks array field.
Reference

gorm many2many and additional fields in association table

I have a many2many association (it is used to return JSON). It's declared in a model:
// models/school.go
type School struct {
ID int `gorm:"primary_key"`
Name string `gorm:"not null"`
Accreditations []Accreditation `gorm:"many2many:school_accreditation;"`
}
It works well. I have the association returned in the json. The problem is that I have an additional field in the school_accreditation table but it isn't included in the response.
I have tried to declare a model for the association like proposed in this answer:
// models/schoolAccreditation.go
package models
import "time"
// many to many
type SchoolAccreditation struct {
StartedAt time.Time `gorm:"not null"`
}
But it doesn't work so far. Is there some additional configuration to declare? Or to modify?
Answering to myself, I added the field in the linked model as "ignore" and it works, the column is automatically retrieved from the association table.
type Accreditation struct {
// "accreditation" table
ID int `gorm:"primary_key"`
Name string
Description string
// "school_accreditation table", so the field is set as ignore with "-"
EndAt time.Time `gorm:"-"`
}

spring-data-mongo, how to return _id back for saved objects from mongo?

I am newbie to the Spring Data mongo. I have documents which has same FirstName say John, but MiddleName and LastName are different.
Also from UI, some students populating data (feeding data via forms) which has also FirstName say John and again MiddleName and LastName would be different.
Now, when I am saving User Object (which has FirstName, MiddleName, LastName, Age, Sex etc..etc..) into mongo using MongoTemplate. I need to return back "_id" (which mongo create by default if we don't provide it explicitly) of those each saved User object.
Could you please provide any example / guidance? Please help.
If you are saving with mongo template your object Id will be set after insertion (as Oliver Gierke has writen) of the object so you can do it like this.
//User object annotated with #Document
User user = new User(String name);
user.setWhatever(something);
mongoTemplate.save(user);
//now the user object should be populated with generated id;
return user.getId();
but you can use normal CrudRepository and use it with
<mongo:repositories base-package="your.package" />
Spring Data MongoDB will automatically populate the identifier property of your domain object with the generated identifier value.
#Document
class User {
ObjectId id; // by convention, use #Id if you want to use a different name
String firstname, lastname;
…
}
If an object of this class is persisted with the id property set to null, the object will have the property set after it has been persisted via MongoTempalte.
All of this is also described in the reference documentation.

Why I need to specify a name when I create a new model?

I'm just beginning learning MongoDB and Mongoose, I can't get the point of the first argument of model function. Why I need to specify a string as name, and what's its purpose?
// Schema
var CustomerSchema = mongoose.Schema({
name: String
});
// Model, that is the constructor
var Customer = mongoose.model('Customer', CustomerSchema);
// Instance, a particular customer
var john = new Customer({});
The lower-cased, pluralized version of the model name is used for the name of the MongoDB collection it's associated with (e.g. customers in this case).
It also allows your code to look up the model by name via mongoose.model('Customer').

Load Selected Primitive Properties in Entity Framework

I have following structure in Oracle database:
Course(CourseId, Name)
->Student(StudentId, Name, Comment, CourseId)
->Subject(SubjectId, Name, SubjectComment, CourseId)
Student contains some of Primitive Properties (StudentId, Name, CourseId, Comment) and Navigation Property (Courses [Linked with DTO name Course on CourseId]).
Table structure is also same as Entity structure and currenly using Explicit loading to extract the data from Oracle database, using LoadProperty and Load.
I need to load the Collection and Object with selected property, as Load Student with StudentId and Name (without Comment column).
LoadProperty(Student, s => s.Courses), load only CourseId (don't load Name primitive property in Course DTO). So, Student.Courses.First().CourseId will be a value and Name will be null as intentionally excluded from loading from database.
LoadProperty(Course, c => c.Subjects) load only SubjectId without Name property, even don't go to database to load.
Is there any way to Include/Exclude the Primitive types to load?
Not with load property and not with entities. You must create custom query and use projection to load only selected columns:
var student = from s in context.Students
select new {
StudentId = s.StudentId,
... // Other student's properties
CourseId = s.Course.Id,
SubjectIds = s.Courese.Subjects.Select(s => s.Ids)
};