fileLink is not allowed by schema - javascript

I'm trying to use Simple Schema in my current Meteor React project but for some reason I can't get it to work.
This is my schema:
Comments.schema = new SimpleSchema({
city: {
type: String,
label: 'The name of the city.'
},
person: {
type: String,
label: 'The name of the person.'
},
location: {
type: String,
label: 'The name of the location.'
},
title: {
type: String,
label: 'The title of the comment.'
},
content: {
type: String,
label: 'The content of the comment.'
},
fileLink: {
type: String,
regEx: SimpleSchema.RegEx.Url,
label: 'The url of the file.'
},
createdBy: {
type: String,
autoValue: function(){ return this.userId },
label: 'The id of the user.'
}
});
And this is my insert:
createSpark(event){
event.preventDefault();
const city = this.city.value;
const person = this.person.value;
const location = this.location.value;
const title = this.title.value;
const content = this.content.value;
const fileLink = s3Url;
insertComment.call({
city, person, location, title, content, fileLink
}, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
target.value = '';
Bert.alert('Comment added!', 'success');
}
});
}
I'm saving the value I get back from amazon in a global variable called s3Url. I am able to console.log this variable without a problem but when I want to write it to the database I am getting a "fileLink is not allowed by schema" error.
Anyone see what I am doing wrong?
Here is my comments.js file:
import faker from 'faker';
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { Factory } from 'meteor/dburles:factory';
export const Comments = new Mongo.Collection('comments');
Comments.allow({
insert: () => false,
update: () => false,
remove: () => false,
});
Comments.deny({
insert: () => true,
update: () => true,
remove: () => true,
});
Comments.schema = new SimpleSchema({
city: {
type: String,
label: 'The name of the city.'
},
person: {
type: String,
label: 'The name of the person.'
},
location: {
type: String,
label: 'The name of the location.'
},
title: {
type: String,
label: 'The title of the comment.'
},
content: {
type: String,
label: 'The content of the comment.'
},
fileLink: {
type: String,
regEx: SimpleSchema.RegEx.Url,
label: 'The url of the file.'
},
createdBy: {
type: String,
autoValue: function(){ return this.userId },
label: 'The id of the user.'
}
});
Comments.attachSchema(Comments.schema);
And my methods.js file:
import { Comments } from './comments';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { rateLimit } from '../../modules/rate-limit.js';
export const insertComment = new ValidatedMethod({
name: 'comments.insert',
validate: new SimpleSchema({
city: { type: String },
person: { type: String, optional: true },
location: { type: String, optional: true},
title: { type: String },
content: { type: String },
fileLink: { type: String, regEx: SimpleSchema.RegEx.Url },
createdBy: { type: String, optional: true }
}).validator(),
run(comment) {
Comments.insert(comment);
},
});
rateLimit({
methods: [
insertComment,
],
limit: 5,
timeRange: 1000,
});
While working a bit more on it I noticed some things I was doing wrong.
1. I didn't have the right value for my simple schema set up.
2. Some problems have to do with the fact the url has white spaces in it. What can I do to fix this?
3. The current error I am getting is: "Exception in delivering result of invoking 'comments.insert': ReferenceError: target is not defined."

While working a bit more on it I noticed some things I was doing wrong. 1. I didn't have the right value for my simple schema set up. 2. Some problems have to do with the fact the url has white spaces in it. What can I do to fix this? 3. The current error I am getting is: "Exception in delivering result of invoking 'comments.insert': ReferenceError: target is not defined."
Thanks #Khang

Related

Method does not return whole object

When I call the method buildCommand, it does not return the property message, but I found out that if I remove some properties out of buildCommand, it works.
This is the method I call
const buildCommand = (commandJSON) => {
return new Command({
prefix: commandJSON.prefix,
command: commandJSON.command,
aliases: commandJSON.aliases,
parameters: commandJSON.parameters,
message: commandJSON.message,
response: commandJSON.response,
commandMedium: commandJSON.commandMedium,
enabled: commandJSON.enabled,
isDefault: commandJSON.isDefault,
permission: commandJSON.permission,
cooldown: commandJSON.cooldown,
});
};
This is how I call the method
const newCommand = buildCommand(commandJSON);
commandJSON looks like this
{ prefix: '!', command: 'laugh', message: 'hahaha' }
UPDATE 2
Here is my whole Command Model
const mongoose = require('mongoose');
const commandSchema = mongoose.Schema({
prefix: {
type: String,
default: '!',
},
command: {
type: String,
required: true,
},
aliases: {
type: Array,
},
parameters: {
type: Array,
},
message: {
type: String,
},
response: {
type: String,
enum: ['chat', 'whisper'],
default: 'chat',
},
commandMedium: {
type: String,
enum: ['offline', 'online', 'both'],
default: 'both',
},
enabled: {
type: Boolean,
default: true,
},
isDefault: {
type: Boolean,
default: false,
},
permission: {
type: String,
enum: ['everyone', 'subscriber', 'vip', 'moderator', 'broadcaster'],
default: 'everyone',
},
cooldown: {
globalCooldown:{type:Boolean, default:false},
globalDuration:{type:Number, default:0},
userDuration:{type:Number,default:0},
}
});
module.exports = mongoose.model('Commands', commandSchema, 'TwitchUsers');
Command is just a Mongoose model. There's nothing async in there, you can (and should) remove the async/await stuff.
You can simply do const newCommand = new Command(commandJSON), job done.

Limit Depth on Recursive GraphQL Schema Query using graphql-sequelize resolver (Node.js, express-graphql)

I have 2 Models, User and Post. I want to be able to get User information when querying a post, and be able to get all of a User's posts when querying a user.
they have an association as follows:
User.hasMany(Post, {
foreignKey: 'user',
as: 'posts'
});
Post.belongsTo(User, {
foreignKey: 'id',
sourceKey: 'user',
as: 'userObject'
})
Post.addScope('defaultScope', {
include: [{ model: User, as: 'userObject' }],
}, { override: true })
User.addScope('defaultScope', {
include: [{ model: Post, as: 'posts' }],
}, { override: true })
Here are my Models
User.js
module.exports.userType = new GQL.GraphQLObjectType({
name: 'User',
fields: () => {
const { postType } = require('../Post/Post');
return {
id: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'user unique id'
},
ci_username: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
unique: true,
description: 'case INSENSITIVE username of the user'
},
username: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'case SENSITIVE username of the user'
},
password: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'password for the user'
},
first_name: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'first name of user'
},
last_name: {
type: GQL.GraphQLString,
description: 'last name of user (optional)'
},
profile_picture: {
type: GQL.GraphQLString,
description: 'profile picture for the user'
},
posts: {
type: GQL.GraphQLList(postType),
description: 'list of users posts'
}
}
},
})
/** define User model for the database */
module.exports.User = db.define('user', {
id: {
type: Sequelize.UUID,
primaryKey: true,
unique: true,
},
ci_username: {
type: Sequelize.STRING,
unique: true,
},
username: Sequelize.STRING,
password: Sequelize.STRING,
first_name: Sequelize.STRING,
last_name: Sequelize.STRING,
profile_picture: Sequelize.STRING,
}, {
// Tells sequelize not to query the "CreatedAt" or "UpdatedAt" Columns
timestamps: false
})
Post.js
module.exports.postType = new GQL.GraphQLObjectType({
name: 'Post',
fields: () => {
const { userType } = require('../User/User');
return {
id: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'post unique id'
},
name: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'name of the post'
},
user: {
type: userType,
description: 'user object of who created the post'
},
created_at: {
type: new GQL.GraphQLNonNull(GQL.GraphQLString),
description: 'the datetime the post was created',
}
}
},
})
/** define User model for the database */
module.exports.Post = db.define('post', {
id: {
type: DataTypes.UUID,
primaryKey: true,
unique: true,
},
name: DataTypes.STRING,
user: {
type: DataTypes.STRING,
references: {
model: 'users',
key: 'id'
}
},
created_at: {
type: DataTypes.TIME,
defaultValue: DataTypes.NOW
}
}, {
// Tells sequelize not to query the "CreatedAt" or "UpdatedAt" Columns
timestamps: false
})
Here are my Queries:
allUsers.js
const allUsers = {
type: new GQL.GraphQLList(userType),
args: {
username: {
description: 'username of the user',
type: GQL.GraphQLString,
},
// An arg with the key limit will automatically be converted to a limit on the target
limit: {
type: GQL.GraphQLInt,
default: 10
},
// An arg with the key order will automatically be converted to a order on the target
order: {
type: GQL.GraphQLString
}
},
// use graphql-sequelize resolver with the User model from database
resolve: resolver(User)
}
allPosts.js
const allPosts = {
type: new GQL.GraphQLList(postType),
args: {
username: {
description: 'username of the user',
type: GQL.GraphQLString,
},
// An arg with the key limit will automatically be converted to a limit on the target
limit: {
type: GQL.GraphQLInt,
default: 10
},
// An arg with the key order will automatically be converted to a order on the target
order: {
type: GQL.GraphQLString
}
},
// use graphql-sequelize resolver with the Post model from database
resolve: resolver(Post)
}
I'm currently getting a Maximum call stack size exceeded. I assume because the resolver in the queries are recursively getting details on posts and users infinitely.
Does anyone know of any way to put a depth limitation on the resolver? Or is it just not possible to have a recursive query like this?
You would have to remove the default scope from the included model as shown here like this:
Post.addScope('defaultScope', {
include: [{ model: User.scope(null), as: 'userObject' }],
}, { override: true })
User.addScope('defaultScope', {
include: [{ model: Post.scope(null), as: 'posts' }],
}, { override: true })
To support additional depth, you'd need to implement resolvers for the fields in question, for example:
function resolve (user) {
if (user.posts) {
return user.posts
}
return user.getPosts()
}

Handlebars each statement can access data that handlebars won't access directly

I have a simple help desk app I've been building, where user can make request for site changes. One of the features is being able to see all request made by a specific person, which is working. However on that page I wanted to have something akin to "User's Request" where user is the person's page you are on. However I can't seem to get it to work without some weird issues. If I use:
{{#each request}}
{{user.firstName}}'s Request
{{/each}}
It works but I end up with the header being written as many times as the user has request. However, when I tried:
{{request.user.firstName}}
It returns nothing.
My route is populating user data, so I think I should be able to reference it directly. Here's the route:
// list Request by User
router.get('/user/:userId', (req, res) => {
Request.find({user: req.params.userId})
.populate('user')
.populate('request')
.then(request => {
res.render('request/user', {
request: request,
});
});
});
Here's the schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const RequestSchema = new Schema({
title: {
type: String,
required: true,
},
body: {
type: String,
required: true,
},
status: {
type: String,
default: 'new',
},
priority: {
type: String,
default: 'low',
},
project: {
type: String,
default: 'miscellaneous',
},
category: {
type: String,
default: 'change',
category: ['change', 'bug', 'enhancement', 'investigation', 'minor_task', 'major_task', 'question'],
},
organization: {
type: String,
default: 'any',
},
assignedUser: {
type: String,
default: 'venkat',
},
allowComments: {
type: Boolean,
default: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'users',
},
lastUser: {
type: Schema.Types.ObjectId,
ref: 'users',
},
date: {
type: Date,
default: Date.now,
},
lastUpdate: {
type: Date,
default: Date.now,
},
comments: [{
commentBody: {
type: String,
required: true,
},
commentDate: {
type: Date,
default: Date.now,
},
commentUser: {
type: Schema.Types.ObjectId,
ref: 'users',
},
}],
});
// Create collection and add Schema
mongoose.model('request', RequestSchema);
The rest of the code is at: https://github.com/Abourass/avm_req_desk
If anyone is wondering how, the answer was to add the array identifier to the dot path notation:
<h4>{{request.0.user.firstName}}'s Request</h4>

Mongoose create method ignores variable, but not hard coded data

Can someone lead me in the right direction? I'ven been stuck on this a few days. I'm using Express and Mongoose. Here is my controller,
module.exports.addPoll = function(req,res) {
var optionsArray = [];
var row = [];
req.body.option1.forEach( function(value) {
optionsArray.push('{"v":"' + value + '"},{"v":0}');
});
var beg = '{"c":[';
var end = ']}';
var whole = beg.concat(optionsArray, end);
Pol.create({
cols: [{label: "options", type: "string"}, {label: "quantity", type:
"number"}],
rows: whole,
title: req.body.heading
}, function(err, poll) {
if (err) {
sendJSONresponse(res, 400, err);
} else {
sendJSONresponse(res, 201, poll);
console.log(whole);
}
});
}
When i create the document the rows property is empty. It ignores the variable that has the data and looks like this.
{"__v":0,"rows":{"c":[]},"title":"What is tomorrow","_id":"59826915c7a0186940e8431c","cols":[{"label":"options","type":"string"},{"label":"quantity","type":"number"}]}
Here is what it looks like when it logs and if replace the variable withi this, it works perfectly fine. I don't get it.
[{"c":[{"v":"Monday"},{"v":"0"},{"v":"Tuesday"},{"v":"0"}]}]
Here is my schema.
var rowsSchema = new mongoose.Schema({
c: [{
v: {
type: String,
required: true
},
_id:false
},
{
v:{
type:Number,
required: true
},
_id:false
}],
_id: false
})
var pollSchema = new mongoose.Schema({
cols: [{
label: {
type: String,
required: true
},
type: {
type: String,
required: true
},
_id: false
},
{
label: {
type: String,
required: true
},
type: {
type: String,
required: true
},
_id:false
}],
rows: rowsSchema,
title: {type: String, required:true, _id:false}
})

Manipulating Mongoose/MongoDB Array using Node.js

I've noticed there's little documentation and info about how I should manipulate an array of objects using Mongoosejs.
I have the following model/Schema for an User:
'use strict';
/**
* Module Dependencies
*/
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');
var mongoose = require('mongoose');
/**
* Custom types
*/
var ObjectId = mongoose.Schema.Types.ObjectId;
var userSchema = new mongoose.Schema({
email: { type: String, unique: true, index: true },
password: { type: String },
type: { type: String, default: 'user' },
facebook: { type: String, unique: true, sparse: true },
twitter: { type: String, unique: true, sparse: true },
google: { type: String, unique: true, sparse: true },
github: { type: String, unique: true, sparse: true },
tokens: Array,
profile: {
name: { type: String, default: '' },
gender: { type: String, default: '' },
location: { type: String, default: '' },
website: { type: String, default: '' },
picture: { type: String, default: '' },
phone: {
work: { type: String, default: '' },
home: { type: String, default: '' },
mobile: { type: String, default: '' }
}
},
activity: {
date_established: { type: Date, default: Date.now },
last_logon: { type: Date, default: Date.now },
last_updated: { type: Date }
},
resetPasswordToken: { type: String },
resetPasswordExpires: { type: Date },
verified: { type: Boolean, default: true },
verifyToken: { type: String },
enhancedSecurity: {
enabled: { type: Boolean, default: false },
type: { type: String }, // sms or totp
token: { type: String },
period: { type: Number },
sms: { type: String },
smsExpires: { type: Date }
},
friends: [{
friend: { type: ObjectId, ref: 'User' },
verified: { type: Boolean, default: false }
}]
});
/* (...) some functions that aren't necessary to be shown here */
module.exports = mongoose.model('User', userSchema);
So as you can check I defined Friends inside User like this:
friends: [{
friend: { type: ObjectId, ref: 'User' },
verified: { type: Boolean, default: false }
}]
Now the question is how can I add, edit and delete this array in a Node.js script?
BOTTOMLINE: How can I manipulate arrays that are inside MongoDB Schemas, using Node.js and Mongoose.js? Do I always have to create a Schema function or can I access it directly?
EDIT (13/07/2014): So far I've created a HTTP GET that gives me the array like this:
app.get('/workspace/friends/:userid', passportConf.isAuthenticated, function (req, res) {
User.find({_id: req.params.userid}, function (err, items) {
if (err) {
return (err, null);
}
console.log(items[0].friends);
res.json(items[0].friends);
});
});
But this only returns an array of friendIds, but what if I want to create some sort of '/workspace/friends/:userid/del/:friendid' POST, or add POST. I can't seem to figure out how I can get this done.
You can do something like following
app.get('/workspace/friends/:userid/delete/:friendId', passportConf.isAuthenticated, function (req, res) {
User.findOne({_id: req.params.userid}, function (err, user) {
if (err) {
return (err, null);
}
for (var i = 0; i < user.friends.length; i++) {
if (user.friends[i]._id === req.params.friendId) {
user.friends = user.friends.splice(i,1)
}
}
user.save(function(err, user, numAffected){
if (!err )res.json(user)
res.send('error, couldn\'t save: %s', err)
})
});
});
What it says in mongoose docs is that
"The callback will receive three parameters, err if an error occurred, [model] which is the saved [model], and numberAffected which will be 1 when the document was found and updated in the database, otherwise 0.
The fn callback is optional. If no fn is passed and validation fails, the validation error will be emitted on the connection used to create this model."
If you need to manipulate arrays, you should convert these in objects before.
User.findOne({_id: req.params.userid}, function (err, user) {
if (err) {
return (err, null);
}
var user = user.toObject();
//... your code, an example =>
delete user.friends;
res.json(user);
});
Regards, Nicholls

Categories

Resources