So , i don't know how to handle this on a graphql service.
I am migrating a service from rest - express api to an apollo api.
my current mongo schema is like this:
const PostSchema = new mongoose.Schema({
title: { type: String, required: true },
body: { type: String },
uid: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
privacy: { type: String, enum: ['everyone','followers','onlyme'], default: 'everyone' },
});
const UserSchema = new mongoose.Schema({
name: { type: String, required: true },
followers: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
});
in express environment i used to get post with populated user the then apply a privacy control function based on user followers.
but in apollo i cant access post after its populated . where can i apply a directive or something after the post fields is resolved?
graphql schema:
type User {
_id: ID!
name: String
followers: [ID]
}
type Post {
_id: ID!
title: String!
body:String
uid :User #privacy
}
extend type Query{
post(_id: String):Post
posts:[Post]
}
post resolver:
{
Query: {
post: (p, a, ctx, info) => {
return ctx.modules.post.getPost(a._id)
}
},
Post: {
uid: (p, a, ctx, info) => {
return ctx.modules.user.getUser(p.uid);
}
},
}
Related
I have 4 level nested schema:
Framework has Domain referenced to it, Domain has control referenced to it, and Control has SubControl referenced to it.
Now I have been searching for a while and I keep getting confused.
First question: is it possible to post all the data from the framework it self?
Second question: I have used referencing with ID approach, should I switch to using subDocuments?
Framework Schema:
const FrameworkSchema = new Schema({
name: {
type: String,
trim: true
},
description: {
type: String,
trim: true
},
domain: [{
domain: {type: Mongoose.Schema.Types.ObjectId, ref: 'Domain'}
}],
updated: Date,
created: {
type: Date,
default: Date.now
}
});
module.exports = Mongoose.model('Framework', FrameworkSchema);
Domain Schema:
const DomainSchema = new Schema({
_id: {
type: Schema.ObjectId,
auto: true
},
domainNo: {
type: String,
trim: true
},
domainName: {
type: String,
trim: true
},
domainDescription: {
type: String,
trim: true
},
framework: {
type: Mongoose.Schema.Types.ObjectId,
ref: 'Framework'
},
control: [{
control: {type: Mongoose.Schema.Types.ObjectId, ref: 'Control'}
}],
updated: Date,
created: {
type: Date,
default: Date.now
}
});
module.exports = Mongoose.model('Domain', DomainSchema);
My control Schema:
const ControlSchema = new Schema({
_id: {
type: Schema.ObjectId,
auto: true
},
mainControl: {
type: String
},
subControl: [{
subControlNo: {type: Mongoose.Schema.Types.String, ref: 'SubControl'}
}],
controlDescription: {
type: String,
trim: true
},
updated: Date,
created: {
type: Date,
default: Date.now
}
});
module.exports = Mongoose.model('Control', ControlSchema);
My SubControl Schema
const SubControlSchema = new Schema({
_id: {
type: Schema.ObjectId,
auto: true
},
subControlNo: {
type: [String]
},
updated: Date,
created: {
type: Date,
default: Date.now
}
});
module.exports = Mongoose.model('SubControl', SubControlSchema);
Now I'm trying to post this nested documents from the framework api:
router.post(
'/add',
auth,
role.checkRole(role.ROLES.Admin), async (req, res) => {
try {
const subControl = new SubControl({...req.body});
const subControlDoc = await subControl.save();
const control = new Control({...req.body}); // take the control data
control.subControl.push(subControlDoc._id); // take the subControl and push the ID into the control
const controlDoc = await control.save();
//make the subcontrol pushed into control
// make control pushed in domain
const domain = new Domain({...req.body});
domain.control.push(controlDoc._id);
const domainDoc = await domain.save();
const framework = new Framework({...req.body});
framework.domain.push(domainDoc._id);
const frameworkDoc = await framework.save(); //save the framework + domain's ID
res.status(200).json({
success: true,
message: `Framework has been added successfully!`,
framework: frameworkDoc
});
} catch (error) {
res.status(400).json({
error
// error: 'Your request could not be processed. Please try again.'
});
}
}
);
Now I'm using push to push the data as an array, not sure if this the right approach, and Is it possible to post the all the data from the framework api?
Tried to post this from postman:
{
"name": "ISO780001",
"description": "frameworkDescription",
"domain":
[
{
"domainNo": "11",
"domainName": "domainName00",
"domainDescription": "domaindescu0",
"control": [{
"mainControl": "1-4",
"subControl": [{
"subControlNo": "1-4-1"
},
{
"subControlNo": "1-4-2"
}],
"controlDescription": "controlDescriptionTest"
},
{
"mainControl": "1-4",
"subControl": [{
"subControlNo": "1-4-1"
},
{
"subControlNo": "1-4-2"
}],
"controlDescription": "controlDescriptionTest"
}
]
},
{
"domainNo": "1-2",
"name": "domainName00",
"description": "domaindescu0",
"control": {
"mainControl": "1-4",
"subControl": [{
"subControlNo": "1-4-1"
},
{
"subControlNo": "1-4-2"
}],
"controlDescription": "controlDescriptionTest"
}
}
]
}
Only the id's of the domain, control, and subControl get saved in mongodb, is this the how it works can I post all the data from one model in this case the framework? or should I use embedded approach ?
What I will do in scenario where i have alot of references (mongoose name it ref by the way, which allows you to populate).
Example of a frameWork schema with domain reference.
const frameworkSchema = mongoose.Schema({
domains: [{type: mongoose.Schema.Types.ObjectId, ref: 'Domain'}],
})
const FrameworkModel = mongoose.model('Framework', frameworkSchema)
Domain above refers to a Domain model. We can create a domain model now.
const domainSchema = mongoose.Schema({
_id: { type: mongoose.Schema.Types.ObjectId } //this is the default
})
const DomainModel = mongoose.model('Domain', domainSchema);
Example Usage - We want to get all the domain information related to a specific schema.
const results = FrameworkModel.findOne({ _id: 'some framework id'}).populate('domains').lean({ virtuals: true });
The results will be something like
{
_id: 'some framework id',
name: 'name of framework',
domains: [
{
_id: 'id of domain 1',
name: 'example.com'
},
{
_id: 'id of domain 2',
name: 'example2.com'
}
]
}
You can also explore virtuals to see how you can maintain your framework, domains and other controls as separate collections, in order to easily reference to them. This is a better design than nesting multiple levels in a single document.
Unless where necessary, using separate collections has more benefits than using subdocuments. (easier to find documents and easier to update documents, and of course, more performant)
I'm trying to have each record attached to a user who created it,
and every user have their records attached.
Here are my schemas:
1.The Records schema:
const mongoose = require('mongoose')
const RecordsSchema = new mongoose.Schema(
{
Title: { type: String, required: true },
postedby:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
}],
Author: { type: String, required: true},
ISBN: { type: String, required: true },
Review: { type: String },
SelectedFile: { type: String },
Likes: { type: Number, default:0},
Date: { type: Date, default: Date.now()}
});
module.exports = Records = mongoose.model('record', RecordsSchema', 'record');`
Here is the The user Schema:
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema(
{
username: { type: String},
email: { type: String, required: true ,unique:true},
records:[{
type: [mongoose.Schema.Types.ObjectId],
ref: 'record' }],
password: { type: String, required: true},
Date: { type: Date, default: Date.now(), immutable: true }
});
module.exports = User = mongoose.model('user', userSchema,'user');
The express route for getting a record:
router.get('/postedby/', (req, res) => {
Records.find(req.params.id)
.populate('postedby')
.exec()
.then(post =>{
if (!post) {
return res.status(400).json({ msg: 'Add Posts' });
}
else return res.json(post);
}).catch (err => console.error(err))
});
Result of the route:
{
"postedby": [],
"Likes": 0,
"_id": "5fed8c12a4fb2c1e98ef09f6",
"Title": "New Age",
"Author": "Situma Prisco",
"ISBN": "23422",
"SelectedFile": "",
"Review": "",
"Date": "2020-12-31T08:30:10.321Z",
"__v": 0
},
I'm getting a blank Array on the populated user field(posteddby) .
Please help, What am I doing wrong? And yes, i do have a User Logged in
You are too close.
In your schema definition, postedby field itself is an array. Hence you can simply define it like :
postedby:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
}]
Make sure that the ObjectID is stored properly in the postedby array.
Also, you are trying to find a single record based on the ID, hence you can use findById(req.params.id) or findOne({_id:req.params.id}) which would return a single document.
In this I am using nodejs with express and mongoose. My question is how does changing the secondaryUser field affect whether or not the findOne works? If I have it as friends.id it works and it finds the right profile, but I want to tie it to the user field in the profile. If I change it to friends.user.id the findOne fails and it sends the 404 error in the catch.
router.post(
"/:handle",
passport.authenticate("jwt", {
session: false
}),
(req, res) => {
Profile.findOne({ handle: req.params.handle }).then(friends => {
const newFriend = new Friend({
initialAccepted: true,
initialUser: req.user.id,
secondaryUser: friends.id
});
newFriend
.save()
.then(Friend => res.json(Friend))
.catch(err =>
res.status(404).json({
friendnotfound: "No people found with that handle"
})
);
});
}
);
The schema used for friend is
const FriendSchema = new Schema({
initialUser: {
type: Schema.Types.ObjectId,
ref: "profile"
},
secondaryUser: {
type: Schema.Types.ObjectId,
ref: "profile"
},
initialAccepted: {
type: Boolean,
default: false
},
initialSecondary: {
type: Boolean,
default: false
},
date: {
type: Date,
default: Date.now()
}
});
This is the schema for the profile
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users"
},
handle: {
type: String,
required: true,
max: 40
},
bio: {
type: String
},
platforms: {
type: [String]
},
website: {
type: String
},
social: {
youtube: {
type: String
},
twitter: {
type: String
},
facebook: {
type: String
},
linkedin: {
type: String
},
twitch: {
type: String
}
},
games: [
{
name: {
type: String
},
platform: {
type: String
},
handle: {
type: String
},
rank: {
type: String
}
}
],
date: {
type: Date,
default: Date.now
}
});
Follow proper naming convention for variables
Profile.findOne({ handle: req.params.handle }).then(profile => { // changed name from friends to profile
const newFriend = new Friend({
initialAccepted: true,
initialUser: req.user.id,
secondaryUser: profile.id // changed name from friends to profile
// profile.user.id (ref to user table not provided in schema)
});
if you give profile.user.id the object will not get created ( checking for id inside profile schema but user id provided)
Friend Schema:
secondaryUser: {
type: Schema.Types.ObjectId,
ref: "profile" // checking for id inside profile schema
},
I have the following Schema, and Base is the one-for-all collector of info:
const BaseSchema = mongoose.Schema({
creatorId: { type: mongoose.Schema.Types.ObjectId, required: true },
title: { type: String, required: true },
created: { type: Date, default: Date.now() },
users: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
messages: [{ type: mongoose.Schema.Types.ObjectId, ref: "Message" }]
});
And:
const BaseUserSchema = mongoose.Schema({
userId: { type: String },
baseId: { type: mongoose.Schema.Types.ObjectId },
created: { type: Date, default: Date.now() },
acceptedMembership: { type: Boolean, default: false },
isCreator: { type: Boolean, default: false }
});
(I have one for Message which looks about the same)
The latter one is referred to as User in const User = mongoose.model("User", UserSchema);
When I create a new Base I automatically add a user to a list within. In the DB i can see that the user does exist, but when I call the following the field does not populate:
Base.find({ creatorId: req.params.id })
.populate("users", "messages")
.exec()
.then(data => console.log(data));
I get the following from the console.log:
[ { created: 2018-09-05T03:41:45.416Z,
users: [],
messages: [],
_id: 5b8f508b2760c5329c13a9be,
creatorId: 5b86f7970cd98b2004969bf0,
title: 'testBase1',
__v: 1 } ]
When I first create the base via React front-end, and the base gets added to a list, I see that the users.length is 1, or the length of the automatically created user. When I refresh the page, however, the userlist is empty in the console.
Adding:
Forget to show how I populate the userlist upon creation:
router.post("/add", jwtAuth, (req, res) => {
Base.create({
creatorId: req.body.userId,
title: req.body.title
}).then(baseInfo => {
BaseUser.create({
userId: req.body.username,
baseId: baseInfo._id,
created: Date.now(),
acceptedMembership: true,
isCreator: true
})
.then(baseuser => {
baseInfo.users.push(baseuser);
return baseInfo.save();
})
.then(base => res.json(base.serialize()));
});
});
Answer:
.populate("users", "messages")
to begin with will return messages from users. It has to be two separate entries, like so:
.populate("users")
.populate("messages")
Then, in the model
users: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
refers to the wrong ref. It has to be
users: [{ type: mongoose.Schema.Types.ObjectId, ref: "BaseUser" }],
from
const BaseUser = mongoose.model("BaseUser", BaseUserSchema);
At last, I am not sure if this is needed, but I added a ref to each of the to-be-populated items:
baseId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "Base" },
baseId: { type: mongoose.Schema.Types.ObjectId, ref: "Base" },
Now it works like a charm, all without additional fetch
I have a user schema and a post schema, wherein a user has many posts. I would like to return all posts that the user has on a route called '/post/dashboard'.
Here is my schemas:
let UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
default: null,
},
profile_pic: {
type: String,
default: '/img/profilepic.png',
},
posts: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
})
let PostSchema = new Schema({
title: {
type: String,
},
description: {
type: String,
}
original_poster: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
tags: {
type: [String]
}
})
So, for example something like:
app.get('/', (req,res) => {
Post.find({ original_poster: req.session.user }).then((posts) =>{
res.send(JSON.stringify(posts));
}) //where req.session.user is an id (the logged in user's object id or _id)
})
Essentially in sql syntax it might be something like:
SELECT * FROM POSTS WHERE ORIGINAL_POSTER = <req.session.user>
What is the proper way to return all posts by the req.session.user?
It seems that original_poster field represent a reference to User's model, If req.session.user is stored as a string you have to cast it to objectID:
const mongoose = require('mongoose');
...
let userId = mongoose.Types.ObjectId(req.session.user);
Post.find({ original_poster: userId }).then((posts) => {
res.send(JSON.stringify(posts));
});