Schema must be an instance of GraphQLSchema. Ensure that there are not multiple versions of GraphQL installed in your node_modules directory - graphql-js

I have an error in graphiql
"message": "Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory."
I tried find node_modules -name graphql. But I have only one version of graphql.
schema.js
import {
GraphQLObjectType,
GraphQLSchema,
GraphQLInt
} from 'graphql';
let count = 0;
let schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
count: {
type: GraphQLInt,
resolve: function() {
return count;
}
}
}
})
});
export default schema;
package.json
"dependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"express": "^4.16.2",
"express-graphql": "^0.6.11",
"graphql": "^0.11.7",
"mysql": "^2.15.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-relay": "^1.4.1",
"require-clean": "^0.1.3",
"webpack": "^3.8.1",
"webpack-dev-server": "^2.9.5"
}
server.js
import express from 'express';
import graphQLHTTP from 'express-graphql';
var Schema = require('./data/schema');
const GRAPHQL_PORT = 8080;
let graphQLServer;
const graphQLApp = express();
graphQLApp.use('/', graphQLHTTP({
graphiql: true,
pretty: true,
schema: Schema,
}));
graphQLServer = graphQLApp.listen(GRAPHQL_PORT, () => {
console.log(
GraphQL server is now running.
);
});
Server works well And I can get GraphQL server is running in console. But graphiql is showing the error.
Any idea what is wrong in it?

There is syntax error in schema.js. fields is a function property. This works.
let schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: ()=> ({
count: {
type: GraphQLInt,
resolve:()=> {
return count;
}
}
})
})
});
server.js
import Schema from './data/schema';

Related

mongodb atlas database not accepting POST request

I'm currently trying to teach myself REST APIs through following a tutorial and encountering a problem where after trying to send a POST request through Postman, it reaches an error statement. The API accepts the POST json data as it appears in the terminal using console.log(req.body) so I believe its likely a problem with the mongodb connection.
posts.js file:
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
router.get('/', (req, res) => {
res.send('It works!');
});
router.get('/', async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch(err){
console.log("Error 2")
res.status(404).json({message:err});
}
});
router.post('/', async (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
try {
const savedPost = await post.save()
res.json(savedPost);
} catch (err) {
console.log(req.body)
console.log("Error encountered when attempting to POST")
res.status(404).json({ message: err });
}
});
module.exports = router;
app.js:
const express = require('express');;
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
app.use(bodyParser.json());
app.use(express.json());
//import the routes
const postsRoute = require('./routes/posts');
//middleware
app.use('/posts', postsRoute);
//Routes
app.get('/', (req,res) => {
res.send('Welcome to the Home Page');
});
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{useNewUrlParser:true} ,
() => {console.log('Succesfully connected to DB')
});
//Start server listening
console.log('App is running on: http://localhost:3000');
app.listen(3000);
package.json:
{
"name": "api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.2",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"mongoose": "^6.2.9",
"nodemon": "^2.0.15"
}
}
Schema file
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Posts', PostSchema);
console log:
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
App is running on: http://localhost:3000
Succesfully connected to DB
{ title: 'test', description: 'test2' }
Error encountered when attempting to POST

Creating a READSTREAM in GFS is throwing an error, does not seem catchable

I am setting up an up/download and have used several resources. I need to be able to store the "files" in the Mongo datastore and then read them back out. I was able to upload, but downloading is through an error when I try to instantiate the createReadStream.
I have over come most of the other errors in the original code. Here is my Package.json:
{
"name": "downloadtest",
"version": "2.3.0",
"license": "MIT",
"scripts": {
},
"engines": {
"node": "6.11.1",
"npm": "3.10.9"
},
"private": true,
"dependencies": {
"body-parser": "^1.19.0",
"core-js": "3.1.3",
"express": "^4.17.1",
"gridfs-stream": "^1.1.1",
"mongoose": "^5.6.7",
"mongoose-unique-validator": "^2.0.3",
"multer": "^1.4.2",
"multer-gridfs-storage": "^3.3.0",
"path": "^0.12.7",
},
"devDependencies": {
}
}
Here is the code that is throwing the error:
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
mongoose.connect(mongoURI, { useNewUrlParser: true });
let conn = mongoose.connection;
let multer = require('multer');
let GridFsStorage = require('multer-gridfs-storage');
let Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
let gfs = Grid(conn, mongoURI);
let port = 3000;
// Setting up the root route
app.get('/', (req, res) => {
res.send('Welcome to the express server');
});
// Allows cross-origin domains to access this API
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin' , 'http://localhost:4200');
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append("Access-Control-Allow-Headers", "Origin, Accept,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
res.append('Access-Control-Allow-Credentials', true);
next();
});
// BodyParser middleware
app.use(bodyParser.json());
// Setting up the storage element
let storage = GridFsStorage({
gfs : gfs,
url: mongoURI,
options: {
useNewUrlParser: true
},
filename: (req, file, cb) => {
let date = Date.now();
// The way you want to store your file in database
cb(null, file.fieldname + '-' + date + '.');
},
// Additional Meta-data that you want to store
metadata: function(req, file, cb) {
cb(null, { originalname: file.originalname });
},
root: 'fs', //root name for collection to store files into
curCol: 'fs'
});
// Multer configuration for single file uploads
let upload = multer({
storage: storage
}).single('file');
// Route for file upload
app.post('/upload', (req, res) => {
upload(req,res, (err) => {
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0, error_desc: null, file_uploaded: true});
});
});
// Downloading a single file
app.get('/image/:filename', (req, res) => {
console.log('Searching for: '+ req.params.filename);
gfs.collection('fs'); //set collection name to lookup into
/** First check if file exists */
gfs.files.find({filename: req.params.filename}).toArray(function(err, files){
if(!files || files.length === 0){
return res.status(404).json({
responseCode: 1,
responseMessage: "error"
});
}
// create read stream
console.log('Found: ' + files[0].filename)
// console.dir(gfs);
console.dir(files[0])
var readstream = gfs.createReadStream({
filename: files[0].filename,
root: "fs"
});
// // set the proper content type
// res.set('Content-Type', files[0].contentType)
// // Return response
// return readstream.pipe(res);
});
});
app.listen(port, (req, res) => {
console.log("Server started on port: " + port);
});
Finally, here is the error being thrown:
Server started on port: 3000
Searching for: d47e793f3f5492b4e55869d167a471f5_imageThumb.png
Found: d47e793f3f5492b4e55869d167a471f5_imageThumb.png
{ _id:
ObjectID {
_bsontype: 'ObjectID',
id:
Buffer [Uint8Array] [ 90, 104, 195, 29, 197, 30, 94, 0, 20, 99, 208, 206 ] },
filename: 'd47e793f3f5492b4e55869d167a471f5_imageThumb.png',
contentType: 'binary/octet-stream',
length: 13031,
chunkSize: 261120,
uploadDate: 2018-01-24T17:32:14.048Z,
aliases: null,
metadata: null,
md5: '5b314153a6bb0004329ccd1fcf8e037e' }
C:\Users\user\Desktop\downloadtest\node_modules\mongodb\lib\utils.js:132
throw err;
^
TypeError: grid.mongo.ObjectID is not a constructor
I've found a couple of references, but nothing seems to relate. To help troubleshoot, I've put in a couple of console logs and a DIR. I am hitting the DB, I am getting the document.. I just cannot start the read stream.
I found the answer myself, and it was to do with versions and trying to use older models. I found another example that is working. I still need to optimize it.

SequelizeDatabaseError: column does not exist (Postgresql)

I'm using Sequelize with Postgresql DB and ExpressJS.
There are 2 models Manufacturer and ManufacturerTab. These two models are associated with each other. Manufacturer hasMany ManufacturerTab and ManufacturerTab belongsTo Manufacturer.
I'm getting an error while trying fetch the ManufacturerTabs list:
{
"name": "SequelizeDatabaseError",
"message": "column ManufacturerTabs.ManufacturerId does not exist",
"parent": {
"name": "error",
"length": 130,
"severity": "ERROR",
"code": "42703",
"position": "704",
"file": "parse_relation.c",
"line": "3293",
"routine": "errorMissingColumn",
"sql": "SELECT \"Manufacturer\".\"id\", \"Manufacturer\".\"manufacturer_name\", \"Manufacturer\".\"manufacturer_logo_url\", \"Manufacturer\".\"manufacturer_archived_status\", \"Manufacturer\".\"createdAt\", \"Manufacturer\".\"updatedAt\", \"ManufacturerTabs\".\"id\" AS \"ManufacturerTabs.id\", \"ManufacturerTabs\".\"sequence\" AS \"ManufacturerTabs.sequence\", \"ManufacturerTabs\".\"tab_name\" AS \"ManufacturerTabs.tab_name\", \"ManufacturerTabs\".\"createdAt\" AS \"ManufacturerTabs.createdAt\", \"ManufacturerTabs\".\"updatedAt\" AS \"ManufacturerTabs.updatedAt\", \"ManufacturerTabs\".\"ManufacturerId\" AS \"ManufacturerTabs.ManufacturerId\" FROM \"Manufacturers\" AS \"Manufacturer\" LEFT OUTER JOIN \"ManufacturerTabs\" AS \"ManufacturerTabs\" ON \"Manufacturer\".\"id\" = \"ManufacturerTabs\".\"ManufacturerId\";"
},
"original": {
"name": "error",
"length": 130,
"severity": "ERROR",
"code": "42703",
"position": "704",
"file": "parse_relation.c",
"line": "3293",
"routine": "errorMissingColumn",
"sql": "SELECT \"Manufacturer\".\"id\", \"Manufacturer\".\"manufacturer_name\", \"Manufacturer\".\"manufacturer_logo_url\", \"Manufacturer\".\"manufacturer_archived_status\", \"Manufacturer\".\"createdAt\", \"Manufacturer\".\"updatedAt\", \"ManufacturerTabs\".\"id\" AS \"ManufacturerTabs.id\", \"ManufacturerTabs\".\"sequence\" AS \"ManufacturerTabs.sequence\", \"ManufacturerTabs\".\"tab_name\" AS \"ManufacturerTabs.tab_name\", \"ManufacturerTabs\".\"createdAt\" AS \"ManufacturerTabs.createdAt\", \"ManufacturerTabs\".\"updatedAt\" AS \"ManufacturerTabs.updatedAt\", \"ManufacturerTabs\".\"ManufacturerId\" AS \"ManufacturerTabs.ManufacturerId\" FROM \"Manufacturers\" AS \"Manufacturer\" LEFT OUTER JOIN \"ManufacturerTabs\" AS \"ManufacturerTabs\" ON \"Manufacturer\".\"id\" = \"ManufacturerTabs\".\"ManufacturerId\";"
},
"sql": "SELECT \"Manufacturer\".\"id\", \"Manufacturer\".\"manufacturer_name\", \"Manufacturer\".\"manufacturer_logo_url\", \"Manufacturer\".\"manufacturer_archived_status\", \"Manufacturer\".\"createdAt\", \"Manufacturer\".\"updatedAt\", \"ManufacturerTabs\".\"id\" AS \"ManufacturerTabs.id\", \"ManufacturerTabs\".\"sequence\" AS \"ManufacturerTabs.sequence\", \"ManufacturerTabs\".\"tab_name\" AS \"ManufacturerTabs.tab_name\", \"ManufacturerTabs\".\"createdAt\" AS \"ManufacturerTabs.createdAt\", \"ManufacturerTabs\".\"updatedAt\" AS \"ManufacturerTabs.updatedAt\", \"ManufacturerTabs\".\"ManufacturerId\" AS \"ManufacturerTabs.ManufacturerId\" FROM \"Manufacturers\" AS \"Manufacturer\" LEFT OUTER JOIN \"ManufacturerTabs\" AS \"ManufacturerTabs\" ON \"Manufacturer\".\"id\" = \"ManufacturerTabs\".\"ManufacturerId\";"
}
Manufacturer Model:
'use strict';
module.exports = (sequelize, DataTypes) => {
var Manufacturer = sequelize.define('Manufacturer', {
manufacturer_name: DataTypes.STRING,
manufacturer_logo_url: DataTypes.TEXT,
manufacturer_archived_status: DataTypes.BOOLEAN
}, {
classMethods: {
associate: function(models) {
Manufacturer.hasMany(models.ManufacturerTab)
}
}
});
return Manufacturer;
};
ManufacturerTab Model:
'use strict';
module.exports = (sequelize, DataTypes) => {
var ManufacturerTab = sequelize.define('ManufacturerTab', {
sequence: DataTypes.ARRAY(DataTypes.INTEGER),
tab_name: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
ManufacturerTab.belongsTo(models.Manufacturer)
}
}
});
return ManufacturerTab;
};
Manufacturer Tab routes:
var models = require('../models');
var express = require('express');
var router = express.Router({mergeParams: true});
/* Get Manufacturer Tabs List */
router.get('/', function(req, res) {
var manufacturer_id = req.params.manufacturer_id;
models.Manufacturer.findAll({
include: [models.ManufacturerTab]
}).
then(function(manufacturers) {
res.status(200).json(manufacturers);
}, function(error) {
res.status(500).send(error);
});
});
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cors = require('cors');
var routes = require('./routes/index');
var users = require('./routes/users');
var manufacturers = require('./routes/manufacturers');
var manufacturer_tabs = require('./routes/manufacturer_tabs');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors({origin: 'http://localhost:4200'}));
app.use('/', routes);
app.use('/users', users);
app.use('/manufacturers', manufacturers);
app.use('/manufacturers/:manufacturer_id/manufacturer-tabs', manufacturer_tabs);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
// no stacktraces leaked to user unless in development environment
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: (app.get('env') === 'development') ? err : {}
});
});
module.exports = app;
Config.js
module.exports = {
development: {
dialect: "postgres",
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOSTNAME
},
staging: {
dialect: "postgres",
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOSTNAME
},
production: {
dialect: 'postgres',
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOSTNAME
}
};
When we write Manufacturer.hasMany(models.ManufacturerTab) and we query using include, sequelize will assume that ManufacturerTab contains a column called ManufacturerId. This acts as a foreign key on which the join operation can happen.
In the model definition that you have provided
module.exports = (sequelize, DataTypes) => {
var ManufacturerTab = sequelize.define('ManufacturerTab', {
sequence: DataTypes.ARRAY(DataTypes.INTEGER),
tab_name: DataTypes.STRING
}
there is so such column and hence the error.
If you have created your db tables using migrations, you need to define a new column
ManufacturerId: {
type: Sequelize.INTEGER, // or choose what you want
allowNull: false,
references: {
model: 'Manufacturer',
key: 'id',
},
onDelete: 'CASCADE', // or choose what you want to do
You need to specify the foreign key to be used in association otherwise it will use default. Add foreignKey in both has belongsTo and HasMany association.
Manufacturer.hasMany(models.ManufacturerTab, {foreignKey: 'your-foreignKey'})
ManufacturerTab.belongsTo(models.Manufacturer, {foreignKey: 'your-foreignKey'})
Your code does not have anything related to creating connection and association.
Include the following code as a separate file in the directory where you have models
fs.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) &&
(file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

A hook (`http`) failed to load! SailsJs

Iam learning Sails and the last days, I could implement Passport Js Authentication, but today, one error appears. It is weird, becouase I made the same steps, but now, all fails. Do I forget install some dependency?
I dont know where the error may be.
This is the error:
Express midleware for passport
error: A hook (`http`) failed to load!
error: ReferenceError: express is not defined
at Object.module.exports.http.customMiddleware (/home/tatico/estudiomate/config/passport.js:46:12)
at /home/tatico/.npm-global/lib/node_modules/sails/lib/hooks/http/initialize.js:237:33
at arrayEach (/home/tatico/.npm-global/lib/node_modules/sails/node_modules/#sailshq/lodash/lib/index.js:1439:13)
at Function.<anonymous> (/home/tatico/.npm-global/lib/node_modules/sails/node_modules/#sailshq/lodash/lib/index.js:3500:13)
at _afterLoadingSessionHookIfApplicable (/home/tatico/.npm-global/lib/node_modules/sails/lib/hooks/http/initialize.js:224:11)
at /home/tatico/.npm-global/lib/node_modules/sails/lib/hooks/http/initialize.js:31:18
at /home/tatico/.npm-global/lib/node_modules/sails/lib/app/private/after.js:91:14
at /home/tatico/.npm-global/lib/node_modules/sails/node_modules/async/lib/async.js:721:13
at /home/tatico/.npm-global/lib/node_modules/sails/node_modules/async/lib/async.js:52:16
at async.forEachOf.async.eachOf (/home/tatico/.npm-global/lib/node_modules/sails/node_modules/async/lib/async.js:236:30)
at _parallel (/home/tatico/.npm-global/lib/node_modules/sails/node_modules/async/lib/async.js:712:9)
at Object.async.parallel (/home/tatico/.npm-global/lib/node_modules/sails/node_modules/async/lib/async.js:726:9)
at Sails.emitter.after (/home/tatico/.npm-global/lib/node_modules/sails/lib/app/private/after.js:89:11)
at _waitForSessionHookIfApplicable (/home/tatico/.npm-global/lib/node_modules/sails/lib/hooks/http/initialize.js:30:15)
at Hook.initialize (/home/tatico/.npm-global/lib/node_modules/sails/lib/hooks/http/initialize.js:42:7)
at Hook.wrapper [as initialize] (/home/tatico/.npm-global/lib/node_modules/sails/node_modules/#sailshq/lodash/lib/index.js:3250:19)
at /home/tatico/.npm-global/lib/node_modules/sails/lib/hooks/index.js:88:16
at /home/tatico/.npm-global/lib/node_modules/sails/node_modules/async/lib/async.js:52:16
at /home/tatico/.npm-global/lib/node_modules/sails/node_modules/async/lib/async.js:548:17
at /home/tatico/.npm-global/lib/node_modules/sails/node_modules/async/lib/async.js:542:17
at _arrayEach (/home/tatico/.npm-global/lib/node_modules/sails/node_modules/async/lib/async.js:85:13)
at Immediate.taskComplete (/home/tatico/.npm-global/lib/node_modules/sails/node_modules/async/lib/async.js:541:13)
These are my files:
package.json:
{
"name": "estudioMate",
"private": true,
"version": "0.0.0",
"description": "a Sails application",
"keywords": [],
"dependencies": {
"bcrypt": "^1.0.2",
"ejs": "2.3.4",
"grunt": "1.0.1",
"grunt-contrib-clean": "1.0.0",
"grunt-contrib-coffee": "1.0.0",
"grunt-contrib-concat": "1.0.1",
"grunt-contrib-copy": "1.0.0",
"grunt-contrib-cssmin": "1.0.1",
"grunt-contrib-jst": "1.0.0",
"grunt-contrib-less": "1.3.0",
"grunt-contrib-uglify": "1.0.1",
"grunt-contrib-watch": "1.0.0",
"grunt-sails-linker": "~0.10.1",
"grunt-sync": "0.5.2",
"include-all": "^1.0.0",
"passport": "^0.3.2",
"passport-local": "^1.0.0",
"rc": "1.0.1",
"sails": "~0.12.11",
"sails-disk": "~0.10.9"
},
"scripts": {
"debug": "node debug app.js",
"start": "node app.js"
},
"main": "app.js",
"repository": {
"type": "git",
"url": "git://github.com/tatico/estudioMate.git"
},
"author": "tatico",
"license": ""
}
config/passport.js:
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy
bcrypt = require('bcrypt');
passport.use(new LocalStrategy(
function(email, password, done) {
User.findOne({ email: email }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
module.exports = {
providers: {
'github': {},
'facebook': {},
'twitter': {}
},
http: {
customMiddleware: function(app){
console.log('Express midleware for passport');
app.use(express.static('public'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(function(req,res,next){
// Set the loggedUser in locals
// to get it from the view
res.locals.loggedUser = req.user;
next();
});
}
}
};
models/User.js:
module.exports = {
attributes: {
email: {
type: 'email',
unique: true
},
admin: {
type: 'boolean',
defaultsTo: false
},
password: {
type: 'string',
required: true
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
},
// Check a password with the saved one.
validPassword: function(password, callback) {
var obj = this.toObject();
// If there are a callback, compare async.
if (callback) {
//callback (err, res)
return bcrypt.compare(password, obj.password, callback);
}
// Otherwise, compare sync.
return bcrypt.compareSync(password, obj.password);
},
hasPassword: function(){
return !!this.password;
}
},
// Lifecycle Callbacks
beforeCreate: function(values, next) {
hashPassword(values, next);
},
beforeValidation: function(values, next) {
if( values.new_password && values.confirm_password ) {
var newPasswordMatch = values.new_password === values.confirm_password;
if( newPasswordMatch ) {
User.findOne(values.id).done(function(err, user) {
if (err) return next(err);
if( !values.password || user.validPassword(values.password) ){
// If old password is valid.
// Ovewrite password with the new password.
values.password = values.new_password;
// delete new password and confirmation.
delete values.confirm_password;
delete values.new_password;
// Hash the password.
hashPassword(values, next);
}
});
}
} else if (values.id) {
// If we are updating the data but the password is not submited.
User.findOne(values.id).done(function(err, user) {
if (err) {
return next(err);
} else {
// Take the same password user had.
values.password = user.password;
next();
}
});
} else {
next();
}
},
beforeUpdate: function(values, next) {
if(values.password) hashPassword(values, next);
else next();
}
};
var bcrypt = require('bcrypt');
function hashPassword(values, next) {
bcrypt.hash(values.password, 10, function(err, hash) {
if (err) return next(err);
values.password = hash;
next();
});
};
Add var express = require('express'); at top of passport.js

GraphQL, Mongoose Resolver RootQuery Syntax

What does my Resolver Query need to look like in order to return a list in Graphiql of the items in this MongoDB instance.
This is the current resolver which logs all items to the console but does not show up in graphiql.
import { Biz } from './connectors';
const resolvers = {
Query: {
biz(_, { name, address }) {
return Biz.find(function (err, biz) {
if (err) return console.error(err);
console.log(biz);
});
},
},
};
export default resolvers;
The graphiql query and response are here:
type definitions in schema.js
const typeDefinitions = `
type Biz {
name: String
address: String
}
type Query {
biz(name: String, address: String): Biz
}
schema {
query: Query
}
`;
export default [typeDefinitions];
This is the connector:
// businesses in mongo DB
const MONGOLAB_URI = 'mongodb://user:password#ds888878.mlab.com:88778/db';
const mongo = Mongoose.connect(MONGOLAB_URI, function (err, res) {
if (err) {
console.log ('ERROR connecting to: ' + MONGOLAB_URI + '. ' + err);
} else {
console.log ( 'Succeeded connected to: ' + MONGOLAB_URI );
}
});
const BizSchema = Mongoose.Schema({
_id: Object,
address: String,
city: String,
country: String,
heading: String,
headingid: Number,
img_url: String,
name: String,
objectId: String,
phonenumber1: String,
website: String,
latitude: Number,
longitude: Number,
});
const Biz = Mongoose.model('bizs', BizSchema);
export { Biz };
sample object in db
{
"_id": {
"$oid": "573e8c9b1379f0f2fad98290"
},
"accountid": 1404,
"address": "737, Grand Rue,",
"city": "Port-au-Prince",
"country": "Haiti",
"createdAt": "10/26/2015 7:27:42 PM",
"heading": "Computer, Printers and Supplies",
"headingid": 323,
"img_url": "https://res.cloudinary.com/klik-io/image/upload/v1454850817/pages-jaunes-haiti-icon_sosoco.png",
"name": "A & M Entreprises",
"objectId": "0lw9lVl23j",
"phonenumber1": "+509 3770 0303",
"website": "http://868.ht"
}
This is the server.js file.
import express from 'express';
import { apolloServer } from 'apollo-server';
import Schema from './src/data/schema';
// import Mocks from './data/mocks';
import Resolvers from './src/data/resolvers';
const GRAPHQL_PORT = 8080;
const graphQLServer = express();
graphQLServer.use('/graphql', apolloServer({
graphiql: true,
pretty: true,
schema: Schema,
resolvers: Resolvers
// allowUndefinedInResolve: true,
// printErrors: true,
// mocks: Mocks,
}));
graphQLServer.listen(GRAPHQL_PORT, () => console.log(
`GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`
));
I resolved the issue in the root query. I noted that posts in the docs returned a post array, [Post] and applied that concept.
In schema.js, I changed Query to an array with [Biz]:
type Query {
biz(name: String, address: String): [Biz]
}
then in resolvers.js I changed the resolvers.Query return statement syntax to the following:
Query: {
biz(_, {name, address}) {
return Biz.find();
}
}