This is the message schema I have been using so far...
{
sender: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: [true, "Please Provide Sender"],
},
content: {
type: String,
max: [2000, "Message can't be longer than 2000 characters"],
trim: true,
required: [true, "Please provide Message"],
},
chat: {
type: mongoose.Schema.Types.ObjectId,
ref: "Chat",
required: [true, "Please Provide Chat Details"],
},
readBy: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
],
}
Now I'd also like to add polls to the chat so
What is the correct way to do that?
One way that I can come up with is to add a type option. And based on that type the message schema changes, but I don't know how to do that...
{
sender:{...},
chat:{...},
readBy:{...},
typeOfMessage:{
........?[prabably a enum of normal string messages and polls object]
........?[also what type (talking about type field) it should have like object or what...]
},
....
content:{
.......?[and based on typeOfMessage my content will be string or object]
}
}
If you find it difficult to understand what I am asking for, tell me.
Thanks
I think that i have to create another schema for polls then add that in my typeOfMessage enum and mongoose validater for validating fields of content according to typeOfMessage value.
Related
I'm doing practices with sequencing and I found a problem that I don't know, or rather I can't understand how to solve it, I have a table that I want to use just to relate 2 other table.
const TagRelations = Sequelize.define(
"tag_relations",
{
entry_id: {
type: sequelize.INTEGER,
references: { model: "entries", key: "id" },
allowNull: false
},
tag_id: {
type: sequelize.INTEGER,
references: { model: "tag", key: "id" },
allowNull: false
}
},
{
// options
underscored: true
}
Entries.hasMany(TagRelations);
Tag.belongsToMany(Entries, { through: TagRelations });
This is how you can see an api practice of a simple blog, I know that the associations use them internally in sequelize when calling it in the controller to be able to do:
include:[{
model: Category,
required: true
}]
and I the data of the category related to an entry, but I don't understand how to call the related tags in this way, I have a block with this topic, so if someone with more experience could explain to me how to handle this detail or indicate if it necessary, structure it in another way, we would appreciate it.
I am trying to use GraphQL to deal with some JSON data. I can retrieve fields from the top level no problem. I can associate separate JSON objects also no problem. My problems are occurring trying to get at data one level down. So, I have defined a type in my schema for staff. The json looks like this:
"staff": [
{
"id": 123,
"name": "fred",
"role" : "designer",
"address": {
"street": "main street",
"town": "Springfield"
}
},
...
]
and the corresponding type in the schema looks like this so far:
const StaffType = new GraphQLObjectType({
name: 'Staff',
fields: {
id: {type: GraphQLInt},
name: {type: GraphQLString},
role: {type: GraphQLString}
}
})
This works fine as far as retrieving the id, name and role goes. My question is how can I extend StaffType to also retrieve street and town from the address field in the original JSON?
Thanks
Ok, I figured it out. I was getting hung up on the idea of a distinct Type in the schema having to refer to a separate piece of JSON whereas, in fact, I can define an AddressType in the schema to refer to the nested data and then include it in the StaffType without having to write a resolve function.
[edit to add example]
const StaffType = new GraphQLObjectType({
name: 'Staff',
fields: {
id: {type: GraphQLInt},
name: {type: GraphQLString},
role: {type: GraphQLString},
address: {type: AddressType}
}
})
const AddressType = new GraphQLObjectType({
name: 'Address',
fields: {
street: {type: GraphQLString},
town: {type: GraphQLString}
}
})
hi i am using MEAN STACK i want to validate JSON keys that comes from front end against mongoose schema. I am validating values but how shall i validate keys that com from client side for example.
var CategorySchema = new Schema({
name: {
type: String,
lowercase: true,
default: '',
trim: true,
unique: [true, 'Category name already exists'],
required: [true, 'Category Name cannot be blank'],
minlength: [4, 'Minimum 4 characters required'],
maxlength: [12, 'Category name cannot be That long']
},
parentCategory: {
type: String,
lowercase: true,
default: '',
trim: true
},
description: {
type: String,
lowercase: true,
default: '',
trim: true,
required: [true, 'description cannot be blank'],
minlength: [10, 'Very short description']
},
imageUrl: {
type: String,
default: '',
trim: true
}
});
what if i am providing this format
{
"IMAGEURL": "c:\abc.png", instead of imageUrl
"DESCRIPTION": "here is some description", INSTEAD OF description
"PARENTCATEGORY": "Men Wear", instead of parentcategory
"Name": "Shirts" instead of name
}
i am writing rest api that will be authenticated is it necessary to check these things. kindly help
For me json schema is so complicated. I suggest to use Json Pattern Validator
npm install jpv
it is very simple to use without any additional keys, and has many patterns to describe json.
import jpv from 'jpv';
var json = {
status : 'OK',
data : {
url : 'http://example.com'
}
}
var pattern = {
status : /^OK$/,
data : {
url : "[url]"
}
}
console.log( jpv.validate(json, pattern ) )
I'm programming a function in order to update users' info. I did it and it works fine however it doesn't work when I want to use custom schemas. I checked the reference but it showed an error "Invalid Input: [employmentData] "
function directoryUpdate(userId, userDept, userLocation, userPhone,userTitle) {
var userId = 'devtest#pruebatest.com',userDept='D003', userLocation='L003';
var userTitle='T003';
var update = {
ims:
[{
type: "work",
protocol: "gtalk",
im: "liz_im#talk.example.com",
primary: true
}],
emails: [
{
address: "liz#example.com",
type: "home",
customType: "",
primary: true
}
],
addresses:
[{
type: "home",
customType: "",
streetAddress: "1600 Amphitheatre Parkway",
locality: "Mountain View",
region: "CA",
postalCode: "94043"
}
],
organizations:
[{
name: "Next Step",
title: userTitle,
primary: true,
type: "work",
department: userDept,
location: userLocation
}],
customSchemas: {
employmentData: {
employeeNumber: "123456789",
jobFamily: "Engineering",
location: "Atlanta",
jobLevel: 8,
projects: [
{ value: "GeneGnome", customType: "development" },
{ value: "Panopticon", customType: "support" }
]
}
}
};
update = AdminDirectory.Users.patch(update, userId);
Logger.log('User %s updated with result %s.', userId, update)
return true;
}
What's the error?
Greetings, Thanks in advance.
The employmentData field is inside the "customSchemas" field. Custom schemas have to be defined before using them.
To create a Custom Schema you have to use the resource Schemas.insert.
After creating the schema with the correspondent fields and type of value (STRING, INT, ETC) your code should run without issues. I tried it and worked for me.
Also, after updating the user, when making the call to Users.get, you have to set the parameter "projection=full" in order to see these values in the response.
I've been struggling for hours to get the simplest populate() query working on my new sails.js project. The problem is that the field to populate always has an empty array. I've pored over the examples, so I don't think I have a syntax error, but maybe my tired eyes aren't letting me see.
Here are the two models + method that's making the query:
Model Department:
attributes: {
id: {
type: 'integer',
primaryKey: true
},
name: {
type: "string",
required: true
},
shortName: {
type: "string"
},
schoolName: {
model: 'Schools'
},
courses: {
collection: 'Courses',
via: "departmentId"
}
},
Model Courses:
attributes: {
id: {
type: "integer",
primaryKey: true
},
name: {
type: "string",
required: true
},
shortName: {
type: "string"
},
departmentId: {
model: "Departments"
}
},
And finally, the method making the call:
getDepartmentsBySchool: function(schoolName, callback){
Departments.find({schoolName: schoolName}).populate("courses").exec(function(error, departments){
if(error){
console.log("Departments could not be found");
return callback(error, []);
} else{
console.log(departments.length + " departments found");
return callback(null, departments);
}
});
}
Result:
courses: []
always.
I am using MySQL, so the adapter is sails-mysql. Any sort of pointer would be greatly appreciated so that I don't have to move away from using this framework.
EDIT:
Changing the migration to "alter" results in the following:
!http://tinypic.com/r/9kv9ev/8
I tested the code sample provided by you at my end. Instead of keeping shoolName as a reference to another collection, I had kept it as string since I wanted to test the association between departments and courses. Everything seems to work fine. Courses were getting populated perfectly. You might wanna check one thing. While using associations of the type:
schoolName: {
model: 'Schools'
},
the schoolName must contain the id of record from schools table. I hope you are setting that up correctly.
Sometimes it can be an issue related to the node module sails-mysql. You may try reinstalling sails-mysql module
npm uninstall sails-mysql
npm cache clear
npm install sails-mysql
Let me know if this works or not.