on mongo db compass I'd like to use a validation schema but on of my properties is an enum, depending on this field another field can be toggled I was able to do this using JSON schema but it dosen't seems to be working on mongoDB compass why ?
{
type: 'object',
properties: {
type: {
enum: ['teacher', 'student']
},
firstname: {
type: 'string',
},
lastname: {
type: 'string',
},
login: {
type: 'string',
},
pwd: {
type: 'string'
},
"if": {"properties": {"type": {"const": "student"}}},
"then": {"properties": {classes: {type: "array"}}}
},
required: [
'type',
'firstname',
'lastname',
'login',
'pwd',
],
};
No.
The MongoDB documentation indicates that it is using draft 4:
JSON Schema object is formatted according to draft 4 of the JSON Schema standard.
The JSON Schema site says these conditionals are new in draft 7:
New in draft 7 if, then and else keywords
let validator = new Validator(req.body, {
password: "requiredIf:is_login_user,1",
});
Related
I have this mutation set up:
followUser: {
type: UserType,
args: {
_id: { type: GraphQLString },
firebaseUid: { type: GraphQLString },
following: { type: new GraphQLList(GraphQLString)},
},
resolve(parentValue, { firebaseUid, _id, following}) {
const update = {
$set: { "following": [firebaseUid] },
$push: { "following": { firebaseUid } }
}
return UserSchema.findOneAndUpdate(
{ _id },
update,
{new: true, upsert: true}
)
}
},
I'm trying to add new followers into my graphql user's collection. My user model:
const UserSchema = new Schema(
{
firebaseUid: String,
following: [{ type: Schema.Types.ObjectId, ref: 'User' }],
followers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
So at first, the user doesn't have any followers, so it won't have that field yet. When user adds someone to their friends list, thats when the field will appear in mongodb. Right now I'm getting this error:
"message": "'$set' is empty. You must specify a field like so: {$set: {<field>: ...}}",
I'm not sure if I'm doing the $set correctly.
The UserType
const UserType = new GraphQLObjectType({
name: "User",
fields: () => ({
_id: { type: GraphQLString },
firebaseUid: { type: GraphQLString },
following: { type: new GraphQLList(GraphQLString) },
followers: { type: new GraphQLList(GraphQLString) },
...
})
});
edit:
current mongodb data collection:
_id: ObjectId("5e5c24111c9d4400006d0001")
name: "Mr. Smith"
username: "mrsmith"
after running the update
_id: ObjectId("5e5c24111c9d4400006d0001")
name: "Mr. Smith"
username: "mrsmith"
following: ["fdsaduybfeaf323dfa"] // <-- this gets added
Currently mongooses validator is rejecting the update. To fix this you need the following:
You only need to $push since it will automatically create an array if the property does not exist
You should remove the extra { } around the firebaseUid in the $push because otherwise the following array will contain objects with a firebaseUid property instead of directly containing the Uid (or would if the schema validator allowed it)
Mongo ObjectIds can only be converted from strings when they are 12-byte hexadecimal, and firebaseUid is not, so the schema should be typed to String instead of ObjectId as the validator will reject the field for update otherwise.
I created a GraphQL server in combination with Express + MongoDB. I started with the following data model:
const AuthorSchema = new Schema({
name: { type: String, required: true },
age: { type: Number, required: true },
});
Queries + Mutations are working, but I decided to add more fields to the data model:
const AuthorSchema = new Schema({
name: { type: String, required: true },
age: { type: Number, required: true },
bio: { type: String, required: true },
picture: { type: String, required: true }
});
I can add a new author through a mutation with the new fields, but for some reason, queries will not return the new fields.
{
"errors": [
{
"message": "Cannot query field \"bio\" on type \"Author\".",
"locations": [
{
"line": 3,
"column": 5
}
]
}
]
}```
Your GraphQL types are not the same as your Mongoose schemas. If you add a field to AuthorSchema schema and want to also expose this as a field on your Author type, then you need to explicitly define the field in your GraphQL schema.
We have been running an app on sailsJS 0.12 -
once 1.0 was released ran through the upgrade process and upgraded
previously, some of the models were supporting "array" type, it's no longer supported. what's the alternative to this ? it's not covered in sample app or the documentation
model I have is :
module.exports = {
attributes: {
provider: 'string',
uid: 'string',
email: 'string',
name: 'string',
firstName: 'string',
lastName: 'string',
password: 'string',
projects: {
collection: 'project',
via: 'owner'
},
creditsHistory:{
collection: 'creditsHistory',
via: 'owner'
},
userRoles: {type: 'array', defaultsTo : [roles.USER]}
},
supported types in sails 1.0 are : https://sailsjs.com/documentation/concepts/models-and-orm/attributes
there isn't any example or sample on what to replace the array type with
sails 0.12 supported types:
https://0.12.sailsjs.com/documentation/concepts/models-and-orm/attributes
does anyone has any idea on this ?
You can use it like that:
'coordinate': {
'type': 'json',
'required': true,
},
Or you can use it like this :
'cost_price': {
'type': 'ref',
'columnType': "double"
},
in colunmType you can define database colunm type
I'm using js-data with the mongodb adapter js-data-mongodb. I'm running into an issue where store.findAll is only returning the _id of the record. No other fields are returned.
Here is my record in my artworks collection in mongoDB:
_id: ObjectId("59bb7ee069d99027f5219667")
uid :"599b73c285b13252e7f54161"
title: "t1"
description: "t1"
imageUrl: "this.artwork.imageUrl"
videoUrl: "this.artwork.videoUrl"
Part of my js-data store definition:
// Create a store to hold your Mappers
const store = new Container({});
// Mappers in "store" will use the MongoDB adapter by default
store.registerAdapter('mongodb', adapter, { 'default': true });
store.defineMapper('artwork', {
collection: 'artworks',
schema: artworkSchema,
idAttribute: '_id'
});
And the code in my app:
store.findAll('artwork', {uid: '599b73c285b13252e7f54161'}).then((records) => {
console.log(records);
})
The output:
[ Record { _id: '59bb7ee069d99027f5219667' } ]
What am I missing in order to get all the fields of the record returned in the response?
Thanks!
Update:
Turns out if I remove my schema definition from the mapper, the fields are returned correctly. This is my schema definition. I'm not sure where I'm going wrong here.
const artworkSchema = new Schema({
$schema: 'http://json-schema.org/draft-06/schema#',
title: 'Artwork',
description: 'Schema for Artwork records',
type: 'object',
properties: {
uid: { type: 'string' },
title: { type: 'string' },
description: { type: 'string' },
imageUrl: { type: 'string' },
videoUrl: { type: 'string' }
},
required: ['uid', 'title', 'imageUrl', 'videoUrl']
});
Argh, that was silly of me. The findAll() call was returning an array of Records, with its attributes. The console.log() wasn't showing it but I am able to get the data by using the array index (records[0].title) or using get('title') as described in the documentation.
I'm giving a try to the beta version of SailsJS (v1.0.0-32) and I'm having some issues while configuring a custom id. Bellow you'll find my current configuration:
The modelExample.js
module.exports = {
attributes: {
id:{
type: 'string',
columnName: '_id'
},
attr: {
type: 'number'
}
}
}
The model config config/models.js
attributes: {
createdAt: { type: 'number', autoCreatedAt: true, },
updatedAt: { type: 'number', autoUpdatedAt: true, },
id: { type: 'string', columnName: '_id' },
}
The element trying to be inserted:
{id:"600000", attr:40}
The error I get when trying to create a record with an attribute "id" included in the element trying to be created:
AdapterError: Unexpected error from database adapter: Invalid primary key value provided for `id`. Cannot interpret `600000` as a Mongo id.
(Usually, this is the result of a bug in application logic.)
Seems that mongo does not like the string 600000 as an id, but I'm not sure if maybe I'm misunderstanding something related to ids in mongo. In the old version of sails, I never had this issue since the id override was straightforward.
For more information, the sails-mongo adapter version is: "sails-mongo": "^1.0.0-5"
In order to use non-ObjectID primary keys with sails-mongo in Sails 1.0, you have to set dontUseObjectIds: true in your model, for example:
// api/models/User.js
module.exports = {
dontUseObjectIds: true,
attributes: {
id: { type: 'number', columnName: '_id' }, // <-- still need to set `columnName`!
name: { type: 'string' },
...etc...
}
}
This is implemented as of sails-mongo v1.0.0-7.