graphql mongoose must be Output Type but got: undefined - mongodb

schema:
const graphql = require("graphql");
const User = require("../models/user");
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLSchema,
GraphQLID,
GraphQLList
} = graphql;
const CompanyType = new GraphQLObjectType({
name:'Company',
fields: () => ({
name: { type: GraphQLString },
catchPhrase: { type: GraphQLString },
bs: { type: GraphQLString },
})
})
const UserType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id : { type: GraphQLID },
name : { type: GraphQLString },
username : { type: GraphQLString },
email : { type: GraphQLString },
address : { type: GraphQLString },
phone : { type: GraphQLInt },
website : { type: GraphQLString },
company : new GraphQLList(CompanyType)
})
})
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: UserType,
args: {
id: { type: GraphQLID }
},
resolve(parent, args){
return User.findById(args.id);
}
},
users: {
type: new GraphQLList(UserType),
resolve(parent, args){
return User.find({});
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery
});
model:
const mongoose = require('mongoose');
const Scheme = mongoose.Schema;
const userSchema = new Scheme({
id : Number,
name : String,
username : String,
email : String,
address : Object,
phone : Number,
website : String,
company : Object
})
module.exports = mongoose.model('User', userSchema)
Here i am trying to fetch data from mongodb database.
I have setup my server with expressjs with graphql and using mongoose for mongodb client.
But while making quesry in graphiql i am getting below error:
{
"errors": [
{
"message": "The type of User.company must be Output Type but got: undefined."
}
]
}
My result is with nested json so i am using GraphQLList .
Please have a look where i am doing wrong

company : {type: CompanyType}
and schema should be
const userSchema = new Scheme({
id : Number,
name : String,
username : String,
email : String,
address : Object,
phone : Number,
website : String,
company : {
name: String,
catchPhrase: String,
bs: String
}
})

Related

Re: Correct MongoDb Relationships

Hi clever MongoDB people,
I am extremely new to Mongo DB and am trying to teach myself coding but I am battling with the practical side of collections.
I am attempting to create an employee management system and would like to know how do I get the different schemas/collections to only deal with the individual User’s employees.
A user will register using this schema;
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
lowercase: true,
},
companyName: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
role: {
type: String,
default: "customer",
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const User = mongoose.model("User", UserSchema:
);
module.exports = User;
Then the system takes them to a Profile page where they create a profile;
Profile Schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ProfileSchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
},
contactPerson: {
type: String,
required: true,
},
companyName: {
type: String,
required: true,
},
mobileNo: {
type: String,
required: true,
},
workNo: {
type: String,
},
email: {
type: String,
required: true,
},
industry: {
type: String,
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const Profile = mongoose.model("Profile", ProfileSchema);
module.exports = Profile;
Then they can add their employees.
Employee Schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const EmployeeSchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
},
employeeNo: {
type: String,
},
title: {
type: String,
},
employeeName: {
type: String,
required: true,
},
surname: {
type: String,
required: true,
},
gender: {
type: String,
},
race: {
type: String,
},
passportNo: {
type: String,
},
IDnumber: {
type: Number,
},
DOB: {
type: Date,
},
aka: {
type: String,
},
midName: {
type: String,
},
marriage: {
type: String,
},
passportExpires: {
type: Date,
},
mobileNo: {
type: String,
},
empEmail: {
type: String,
lowercase: true,
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const Employee = mongoose.model("Employee", EmployeeSchema);
module.exports = Employee;
Once an employee has been created there are various schemas connected with the employee, such as Personal contact details schema, Job details schema, Emergency contact details schema and so on.
This is my Emergency contact details schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const EmergencySchema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
},
emergContactPerson: {
type: String,
required: true,
},
emergWorkNo: {
type: String,
},
emergMobileNo1: {
type: String,
required: true,
},
emergMobileNo2: {
type: String,
},
medicAidName: {
type: String,
},
medicPlan: {
type: String,
},
medicMemberNo: {
type: String,
},
medicDepCode: {
type: Number,
},
CreatedAt: {
type: Date,
default: () => Date.now(),
},
UpdatedAt: {
type: Date,
default: () => Date.now(),
},
});
const Emergency = mongoose.model("Emergency", EmergencySchema);
module.exports = Emergency;
My question is How do I create a one-to-many relationship between my schemas so that each User will only see their employees and their personal details?
Please can you help me?

How to I resolve below graphql query in mongodb nested array

my model schema look like this
const mongoose = require("mongoose")
const userSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
select: false,
},
email: {
type: String,
required: true,
unique: true,
match: [
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/,
"Please enter a valid email",
],
},
followers:[
{
type:mongoose.Schema.Types.ObjectId,
ref:"user"
}
],
following:[
{
type:mongoose.Schema.Types.ObjectId,
ref:"user"
}
],
displayName: {
type: String,
required: false,
},
},
{ timestamps: true }
)
module.exports = mongoose.model("user", userSchema)
in this schema all working good like mutation work fine but when i fetch query of all user then in that query followers and following field return null like bellow image
and my graphql query is
const users = {
type: new GraphQLList(UserType),
description: "Retrieves list of users",
resolve(parent, args) {
return User.find()
},
}
and typedef is
const UserType = new GraphQLObjectType({
name: "User",
description: "User types",
fields: () => ({
id: { type: GraphQLID },
username: { type: GraphQLString },
email: { type: GraphQLString },
post:{
type: GraphQLList(PostType),
resolve(parent, args) {
return Post.find({ authorId: parent.id })
},
},
savePost:{
type:GraphQLList(savedPosts1),
resolve(parent, args) {
return SavePost.findById({ authorId: parent.id })
},
},
followers:{
type:GraphQLList(UserType),
},
following:{
type:GraphQLList(UserType)
}
// displayName: { type: GraphQLString },
}),
})
so please tell me how to i resolve that followers and following query in graphql with mongodb and tell me what i write in my userType typedef

Mongoose 'populate()' not populating

So Im building a simple application with the MEARN stack.
The problem is that i want to have the user's information (name,email, etc...) to be put in the 'user' property in the product , and it's not working (Postman request return 500 status Server error) , i don't know what i'm doing wrong , thanks in advance! my code snippets :
My User Model :
const mongoose = require('mongoose')
const UserSchema = mongoose.Schema({
name : {
type: String,
required: true
},
email : {
type: String,
required: true,
unique: true
},
password : {
type: String,
required: true
},
date : {
type: Date,
default: Date.now
},
})
module.exports = mongoose.model('user',UserSchema)
my Product Model :
const mongoose = require('mongoose')
const ProductSchema = mongoose.Schema({
user:{
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
name : {
type: String,
required: true
},
description : {
type: String,
required: true
},
quantity : {
type: Number,
required: true
},
price : {
type: Number,
required: true
},
date : {
type: Date,
default: Date.now
},
})
module.exports = mongoose.model('product',ProductSchema)
and my request :
router.get('/:id', async (req,res) => {
try {
const product = await Product.findById(req.params.id).populate('user')
res.json(product)
} catch (err) {
res.status(500).send('Server Error')
}
})
Your ref value needs to match the name of the model user references. So you need to change it to:
user:{
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
You have to specify the path:populate({path:'user'}) Try :
router.get('/:id', async (req,res) => {
try {
const product = await Product.findById(req.params.id).populate({path:'user'})
res.json(product)
} catch (err) {
res.status(500).send('Server Error')
}
})

MongoDB Mongoose find using Map

I have a mongoose schema like this:
const userSchema = new Schema( {
email:{ type: String, required: true, unique:true, index:true },
mobile:{ type: String },
phone:{ type: String },
firstname: { type: String },
lastname: { type: String },
profile_pic:{type:String},
socialHandles: {
type: Map,
of: String
},
active: {type:Boolean, default:true}
}, {
timestamps: true
} );
I want to query "give me user where socialHandles.instagram=jondoe" how do I do it?
Please help
Mongoose's map becomes a nested object in your database
{ "_id" : ObjectId(""), "socialHandles" : { "instagram": "jondoe" }, ..., "__v" : 0 }
so you can query it by using the dot notation:
let user = await User.findOne({ 'socialHandles.instagram': 'jondoe' });

Schema hasn't been registered for model :mongoose

I have a model like this
const Schema = mongoose.Schema
const fileSchema = mongoose.Schema({
ownerId: { type: Schema.Types.ObjectId },
fileTypeId: { type: Schema.Types.ObjectId },
name: { type: String },
data: { type: Schema.Types.Mixed },
fileSize: { type: Number },
isHashInBlockchain: { type: Boolean },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
})
fileSchema.virtual('file', {
ref: 'filetype',
localField: 'fileTypeId',
foreignField: '_id'
})
fileSchema.set('toObject', { virtuals: true })
fileSchema.set('toJSON', { virtuals: true })
module.exports = mongoose.model('useruploadedfiles', fileSchema)
I am referring filetype collection to this model
But when I run the following query
await File.find(query).populate({ path: 'file' }).select('_id name createdAt updatedAt').sort({ createdAt: -1 }).skip(limit * (pageNumber - 1)).limit(limit)
I am getting the following error
Schema hasn't been registered for model "filetype"
You have to import your model in your root app file.
model.js
const UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
trim: true,
},
name: {
type: String,
required: "Please supply a name",
trim: true
},
});
module.exports = mongoose.model("User", UserSchema);
app.js
mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
mongoose.connection.on('error', (err) => {
console.error(`πŸ™… 🚫 πŸ™… 🚫 πŸ™… 🚫 πŸ™… 🚫 β†’ ${err.message}`);
});
// READY?! Let's go!
require('./models/User')
router.js
const User = mongoose.model("User");
const getUsers = async (req, res) => res.json(await User.find({}));
app.get('/users', getUsers);