make ID field required with MongoEngineObjectType - mongodb

I use graphene with graphene-mongo. My graphql schema has a type similar to this:
type Report {
id:ID!
name:String!
}
My graphene class for this type is
class Product(MongoengineObjectType):
class Meta:
model = MongoProduct
and the mongoengine class is
class MongoProduct(mng.DynamicDocument):
name = mng.fields.StringField(required=True)
How can I make the field id required? GraphiQL shows an exclamation mark next to name, but not next to id.

class MongoProduct(mng.DynamicDocument):
id = ObjectIdField(primary_key=True, required=True) # Optional: Add default=bson.ObjectId
name = mng.fields.StringField(required=True)
id can also be a IntField or a StringField but I'd recommend to stick to an ObjectId

Related

Populate a query in Mongoose with Schema First approach and NestJS

First off I want to say this question is similar to this one which references this one. I have the exact same question as the second link except a notable difference. I'm trying to extend a class generated by NestJS which defines a property.
I'm using NestJs with the Schema first approach found here. I'm also generating a classes file based on my GraphQL Schema.
Here is the Schema:
type Location {
name: String!
owner: User!
}
Which generates the class:
export class Location {
name: string;
owner: User;
}
Now, I want to extend this class so I don't have to repeat the data (there are a lot more fields not shown). I also I want to add fields that live on a document but are not in the schema (_id in this example). Here is my LocationDocument and my schema.
export interface LocationDocument extends Location, Document {
_id: Types.ObjectId
}
export const LocationSchema: Schema = new Schema(
{
name: {
type: String,
required: true,
},
owner: {
type: Types.ObjectId,
ref: 'User',
}
);
Now here is my issue. The generated Location class from the GraphQL schema defines the owner property as a User type. But in reality it's a just a mongodb id until it is populated by Mongoose. So it could be a Types.ObjectId or a User on a UserDocument. So I attempted to define it as:
export interface LocationDocument extends Location, Document {
_id: Types.ObjectId
owner: User | Types.ObjectId;
}
But this throws an error in the compiler that LocationDocument incorrectly extends Location. This makes sense. Is there any way to extend the User Class but say that owner property can be a User Type (once populated by Mongoose) or a mongo object ID (as is stored in the database).
I decided that having a property that can be both types, while easy with Mongoose and JS, isn't the typed way. In my schema I have an owner which is a User type. In my database and the document which extends it, I have an OwnerId. So to people accessing the API, they don't care about the ownerId for the relationship. But in my resolver, I use the Id. One is a Mongo ID type, the other is a User type.

How to pass reference to an object as JSON in a POST in grails

I have 2 classes Person and and Designation. I am using #Resource annotation to make them restful
import grails.rest.Resource
#Resource(formats=['json', 'xml'])
class Person {
String name
static belongsTo = [designation:Designation]
static constraints = { }
}
and Designation class is
import grails.rest.Resource
#Resource(formats=['json', 'xml'])
class Designation {
Long designationId
String name
static constraints = { }
}
Since I'm using grails default resource url mapping like
"/app/person"(resources: "person", includes: ['index', 'show', 'save', 'update', 'delete', 'create', 'patch'])
I want to prform insert to Person object using POST request to /app/person with json data.
Since designation is belongs to another object , I need to pass only a reference to an existing Designation object id
how do i pass this via json? what is the json format to do the same?
or can I access the params in beforeInsert() method of Person class , so that i can manually get designatioId , then find Designation object with that id , then assign it new Person object?
I think if you add:
designation: { id: 123 }
to your person JSON, that should do the trick.

MongoDB id remains null after InsertOneAsync

I have a base class Entity that has a string Id member and a derived class A.
But when creating a new instance of the derived class and using InsertOneAsync to add it to my collection, the document is added to the database with null as the Id value.
Using an ObjectId as the Id does seem to work, but I'm trying to prevent MongoDB dependency in my models.
I also experimented with the following code, but the results are the same:
BsonClassMap.RegisterClassMap<Entity>(cm =>
{
cm.MapIdField(x => x.Id).SetSerializer(new StringSerializer(BsonType.ObjectId));
});
I had the same issue and finally got it to work (with the 2.0 driver) with these attributes:
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
[BsonIgnoreIfDefault]
Or the equivalent BsonClassMap fluent interface:
BsonClassMap.RegisterClassMap<Entity>(cm =>
{
cm.MapIdField(x => x.Id)
.SetSerializer(new StringSerializer(BsonType.ObjectId))
.SetIgnoreIfDefault(true);
});
I tried to get the same working with .ReplaceOneAsync with Upsert on but that always leaves the id still null
Are you trying not to use ObjectID in your model. The ID doesn't have to be an objectID. You can decorate a string field as ID.
I have used string property with [BsonId] attribute without any issues.

jpa select string found in where in caluse

I have a list of strings and i need to search them in my table then construct new class contain key as on of my search strings and value as my pojo if exist or null if not exist.
something like that :
Class MyMapper {
private String identificationKey;
private User user;
// Getter and Setter
}
My Expected Query:
SELECT NEW MyMapper(identificationKey, u) From User u where u.identification IN :identificationKeys
i need to select every identificationKey in identificationKeys even not exist

Getting from ToManyField to Model values

In django, I have two models - User and UserProfile. There may exist zero or one profiles for a particular user. I'm trying to include the information from the UserProfile model directly on the UserResource.
I would like to use the profile ToManyField, if it exists, to access the contents of the associated UserProfile model. I've tried a variety of things in dehydrate, including self.profile.get_related_resource(self) and UserProfile.objects.get(id=...), but I can't seem to find my way from the profile field to the model object. Can anybody help me out?
I'm still new to Python, Django, and Tastypie, so hopefully if I'm doing anything awful somebody will be kind enough to point it out.
The goal is to have JSON that looks like this:
{
resourceUri: /v1/users/1
date_of_birth: Jan 1, 1980
... etc
}
where date_of_birth is a property of the UserProfileResource. I don't want all of the fields from UserProfileResource, and I don't want the UserProfile to be a nested object in the response - I want some fields from UserProfileResource to be top-level fields in the response, so that they look like part of the User resource.
class UserResource(ModelResource):
profile = fields.ToOneField('foo.api.UserProfileResource', 'user', null=True)
class Meta:
queryset = User.objects.all()
resource_name = 'users'
allowed_methods = ['get']
#etc...
class UserProfileResource(ModelResource):
date_of_birth = ...
#etc
I assume you're using Django 1.4 and AUTH_PROFILE_MODULE?
Since the User:UserProfile relationship is 1:1 I would opt for the ToOneField instead. This will serialize as a URI pointer to your UserProfileResource (if one exists.) If you'd like the UserProfileResource field data inline with your UserResource, you can specify full=True in the ToOneField definition. With this method you should not need to override dehydrate.
Also, ensure that the second argument in the ToOneField definition is the User attribute which points to your UserProfile Django model. For example if you have OneToOneField(User, related_name='profile') in your Django model then this attribute should be profile.
class UserResource(ModelResource):
profile = fields.ToOneField('foo.api.UserProfileResource', 'profile',
full=True, null=True)
class Meta:
queryset = User.objects.all()
resource_name = 'users'
allowed_methods = ['get']
If what you're after are specific fields from the UserProfile instance mixed in with your User, you should be able to do something like this:
class UserResource(ModelResource):
date_of_birth = fields.DateField('profile__date_of_birth', null=True)
class Meta:
queryset = User.objects.all()
resource_name = 'users'
allowed_methods = ['get']
fields = ['userfields', 'gohere', 'date_of_birth']