Mongoose/MongoDB Question
I have an Owners model containing basic profile data.
I have a secondary model: OwnersImages
e.g
{
owner: {
type: Schema.Types.ObjectId,
ref: 'Owners'
},
name: String,
imageUrl: String,
},
);
From the client I want to post the imageUrl and the name to the OwnersImages table.
e.g
let values = {
owner: this.state.user._id,
name: this.state.field,
imageUrl: this.state.url
}
axios.post(`${serverPath}/api/addFieldImage`, values)
However Im unsure how best to go about this, link it etc.
I can do a GET request on the Owners table to get the Owner data, but then posting this as part of the values to OwnerImages doesn't successfully link the two tables.
Do i need to just store a string reference to the Owner id in OwnerImages or is there a smarter way of doing this?
Or should I just post the string of the user Id to mongoose and then do a map to the Owner table from within there?
Tried to explain this best way I could but the eyes are tired so please ask if any confusion!
Many thanks
Without seeing your exact setup, I think you could modify this to fit your needs:
// In the Schema/Model files
const ownersSchema = Schema({
// other fields above...
images: [{ type: Schema.Types.ObjectId, ref: 'OwnersImages' }]
});
const ownersImagesSchema = Schema({
// other fields above...
owner: { type: Schema.Types.ObjectId, ref: 'Owners' },
});
// in the route-handler
Owners.findById(req.body.owner, async (err, owner) => {
const ownersImage = new OwnersImages(req.body);
owner.images.push(ownersImage._id);
await ownersImage.save();
await owner.save();
});
As a side-note, I think the Models generally have singular names, so Owner and OwnerImage. The collection will then automatically take on the plural form. Just food for thought.
When you want to load these, you can link them with populate(). Consider loading all of the OwnersImages associated with an Owners in some route-handler where the /:id param is the Owners id:
Owners
.findOne({ _id: req.params.id })
.populate('images')
.exec(function (err, images) {
if (err) return handleError(err);
// do something with the images...
});
Related
I have been having trouble figuring out how to update a User with graphQL. The functionality I'm currently aiming for is for the user to be able to update their account/profile information. I have some things set up for the user like a bio field for their profile, and a profile picture field that's set up to take a URL and display that as their profile picture.
I have no problems when it comes to creating using graphQL. A user can sign up, log in, make posts, etc without issue. I can also update the User in regards to other models, for example, a new post pushes to the users Post data just fine.
I have not been able to figure out how to update a user directly though. Essentially I can get around this by creating a new model for "profile pic" and pushing that to the User, but that seems like it's just extra steps that might slow things down, as well as shortchanging myself being able to learn something new.
This is the User model. I have omitted a few fields due to the exact block of code being large, but this includes the "image" and "bio" fields (the fields I would like to update) as well as the reference to the Post model which I mentioned above that functions appropriately.
User.js
const userSchema = new Schema(
{
username: {
type: String,
required: true,
unique: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
match: [/.+#.+\..+/, 'Must match an email address!']
},
password: {
type: String,
required: true,
minlength: 8
},
image: {
type: String
},
bio: {
type: String,
maxLength: 500
},
posts: [
{
type: Schema.Types.ObjectId,
ref: 'Post'
}
],
},
Below is the mutation in Explorer, including the variables and the result.
Profile Pic Resolver
addProfilePic: async (parent, { image }, context) => {
if (context.user) {
const updatedUser = await User.findOneAndUpdate(
{ _id: context.user._id },
{ image: image },
{ new: true, runValidators: true }
);
return updatedUser;
}
throw new AuthenticationError('You need to be logged in!');
},
typeDefs.js (relevant only)
type Mutation {
addProfilePic(_id: ID!, image: String!): Auth
}
I notice that in the Explorer page it returns "null" for user with a 200 status. I am led to believe that means that it's not able to even access the "image" field on the user to be able to update it. When compared to my other mutations in regards to users, this is set up very similarly and I'm not sure what the difference is.
I feel like I am missing something very basic here in regards to being able to update. I haven't been able to find an update mutation example that works. Could anyone assist? My main questions would be:
Why does the mutation return "null" for user?
How can I set up my resolver to appropriately update information on an already-created object?
Thank you to anyone who is able to take a look and assist, I will be closely watching this post for replies and will update any other code someone may need to be able to assist. I've been stuck in regards to updating information for a long time, but my site is getting to the point where it's nearly ready and I need to tackle this updating issue in order to progress. Thank you!
Quick Edit: I want to add that "Auth" is referenced. The appropriate authorization headers are in place to retrieve the data. Just wanted to add that in as I highly doubt authorization has anything to do with this!
I have solved this issue and would like to leave the answer here for anyone who may find it useful.
In the mutation typeDefs, I changed the "Auth" to "User",
type Mutation {
addProfilePic(_id: ID!, image: String!): User
}
and then in the mutation itself, took away the user field like such:
mutation addProfilePic($_id: ID!, $image: String!) {
addProfilePic(_id: $_id, image: $image) {
_id
username
image
}
}
This has allowed the user to update their profile photo information. Hope this helps!
I'm a student working on a chat application for my internship, where I use socket.io.
Right now I am busy thinking of a good way to store the messages send in conversations.
As of now I do the following:
For each conversation between one user and another user, a new collection is made.
On every message sent, the message is stored in the according conversation collection in a single document.
The collections:
Where the document looks as follows:
Now I wonder if there is a good argument to be made to have just one collection "conversations", and store all the messages in multiple documents, where each conversation is a new document.
Creating a new collection for every message is very bad idea instead of that you use a simple schema as given below to store your messages
const conversation_schema = new Schema({
from: {
type: ObjectID,
ref: 'User'
},
to: {
type: ObjectID,
ref: 'User'
},
messageBody: { // body of the message(text body/ image blob/ video blob)
type: String,
},
messageType: { // type of the message(text, mp3, mp4, etc...)
type: String,
},
read: { // to boolean flag to mark whether the to user has read the message
type: Boolean,
default: false,
},
createdAt: { // when was this message goit created
type: Date,
default: new Date(),
},
});
you can fetch the conversation between the two users using the following query
conversations.find({
$or: [
{from: 'user1', TO: 'user2},
{from: 'user2', TO: 'user1},
],
}).populate({ path: 'to', model: User })
.populate({ path: 'from', model: User })
.sort({ createdAt: -1 })
I created a post Schema and I have trouble implementing the comment and comment reply schema since you can not predict how often one comment reply has it own reply.
I am using mongoose and express.
So how can I implement this type of schema design?
I think you're looking for something like this where you are referencing comments from within your comment schema.
I added a middleware to pre-populate the replies array when you call .find(). You can add more middleware for other calls like .findOne() etc.
const mongoose = require("mongoose");
const commentSchema = mongoose.Schema(
{
comment: {
type: String,
required: true
},
author: { // To reference the user that left the comment. If needed
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
replies:[{type: Schema.Types.ObjectId, ref: "Comment"}] // Array of comment replies
},
{
timestamps: true,
}
);
// Middleware to populate the replies when you call `find()`
commentSchema.pre('find', function() {
this.populate('replies');
});
module.exports = mongoose.model('Comment', commentSchema);
You can do more in-depth on this post which will show you how to pre-populate the replies field when returning comments etc.
https://www.makeschool.com/academy/track/standalone/reddit-clone-in-node-js/comments-on-comments
Following AWS documentation (https://aws-amplify.github.io/docs/cli-toolchain/graphql > Many-To-Many Connections), I try to understand the workaround example they provide for many to many connections (which seems not supported yet by Amplify).
The schema is:
type Post #model {
id: ID!
title: String!
editors: [PostEditor] #connection(name: "PostEditors")
}
# Create a join model and disable queries as you don't need them
# and can query through Post.editors and User.posts
type PostEditor #model(queries: null) {
id: ID!
post: Post! #connection(name: "PostEditors")
editor: User! #connection(name: "UserEditors")
}
type User #model {
id: ID!
username: String!
posts: [PostEditor] #connection(name: "UserEditors")
}
Using AWS AppSync Console, so far I'm able to:
Create a user using this mutation:
mutation {
createUser(input:{
username: "theUserName"
}){
username
}
}
Create a post using this mutation:
mutation {
createPost(input: {
title: "second post"
}){
title
}
}
But I don't understand how to add multiple editors to a post? So far, I'm able to add editors to a post using PostEditor join, but in their example, there is this statement (which I don't understand very well), so I don't think this is the good approach:
# Create a join model and disable queries as you don't need them
# and can query through Post.editors and User.posts
So I guess that using this join model to perform mutation is not what I have to do. Nevertheless, to be able to create this relation between a post and an editor, I created a mutation (retrieving "postEditorPostId" and "postEditorEditorId" from both previous mutations):
mutation {
createPostEditor(input:{
postEditorPostId: "XXX-XXX-XXX"
postEditorEditorId: "YYY-YYY-YYY"
}){
post {
title
}
editor {
username
posts {
items {
post {
title
}
}
}
}
}
}
Do I need to perform this previous mutation everytime I add a new editor (so the mutation will remain the same but "postEditorEditorId" will change? it seems obviously not a scalable approach, if for example the UI allows an admin to add 50 or more new editors (so it will need 50 mutations).
Finally I can get the information I need using this query:
query{
getUser(id: "YYY-YYY-YYY"){
username
posts {
items {
post {
title
}
}
}
}
}
Is there a better way (I suppose) to add editors to a post?
edit:
Using a promise, I am able to add multiple editors to a post, but it involves to execute as mutation as mutations as there are users:
const users = [{id: "U1", username: "user1"}, {id: "U2", username: "user2"}];
const post = { id: "P1", title: "Post 1" };
/*
After creating two users and a post using the approriate mutations
Using the CreatePost join below to make user1 and user2 editor on Post 1
*/
function graphqlCreatePostEditor(editorID) {
return new Promise((resolve, reject) => {
resolve(
API.graphql(graphqlOperation(createPostEditor, {
input: {
postID: post.id,
}
}))
)
})
}
let promises = users.map(user=> {
return graphqlCreatePostEditor(user.id)
.then(e => {
console.log(e)
return e;
})
});
Promise.all(promises)
.then(results => {
console.log(results)
})
.catch(e => {
console.error(e);
})
Still looking if there is a way to pass an array in a sigle mutation.
For simplicity sake, I'm lets go with a User model and a Project model where a user can have many projects and belong to many projects.
Note: The creation of join table as I've described it here is for the Amplify JS API for React / React Native / JavaScript
User model
type User #model {
id: ID!
username: String!
projects: [UserProject] #connection(name: "UserProject")
}
Project model
type Project #model {
id: ID!
project_title: String!
users: [UserProject] #connection(name: "ProjectUser")
}
Join table
type UserProject #model {
id: ID!
user: User #connection(name: "UserProject")
project: Project #connection(name: "ProjectUser")
}
Creation of Join table
Prerequisite: Fetch both user.id and project.id however you want to do that.
const UserProjectDetails = {
userProjectUserId: user.id
userProjectProjectId: project.id
};
API.graphql({ query: mutations.createUserProject, variables: {input: UserProjectDetails}})
And there you have it.
This article on dev.to was also pretty straight to the point:
https://dev.to/norrischebl/modeling-relationships-join-table-graphql-aws-amplify-appsync-1n5f
EDIT: Since I wasn't able to find a correct solution, I changed the
application's structure a bit and posted another question:
Mongoose - find documents not in a list
I have a MEAN app with three models: User, Task, and for keeping track of which task is assigned to which user I have UserTask, which looks like this:
const mongoose = require("mongoose");
const autopopulate = require("mongoose-autopopulate");
const UserTaskSchema = mongoose.Schema({
completed: { type: Boolean, default: false },
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
autopopulate: true
},
taskId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Task",
autopopulate: true
}
});
UserTaskSchema.plugin(autopopulate);
module.exports = mongoose.model("UserTask", UserTaskSchema);
In my frontend app I have AngularJS services and I already have functions for getting all users, all tasks, and tasks which are assigned to a particular user (by getting all UserTasks with given userId. For example:
// user-task.service.js
function getAllUserTasksForUser(userId) {
return $http
.get("http://localhost:3333/userTasks/byUserId/" + userId)
.then(function(response) {
return response.data;
});
}
// task-service.js
function getAllTasks() {
return $http.get("http://localhost:3333/tasks").then(function(response) {
return response.data;
});
}
Then I'm using this data in my controllers like this:
userTaskService
.getAllUserTasksForUser($routeParams.id)
.then(data => (vm.userTasks = data));
...and because of autopopulate plugin I have complete User and Task objects inside the UserTasks that I get. So far, so good.
Now I need to get all Tasks which are not assigned to a particular User. I guess I should first get all Tasks, then all UserTasks for a given userId, and then make some kind of difference, with some "where-not-in" kind of filter.
I'm still a newbie for all the MEAN components, I'm not familiar with all those then()s and promises and stuff... and I'm really not sure how to do this. I tried using multiple then()s but with no success. Can anyone give me a hint?
You can do at server/API side that will more efficient.
In client side, if you want to do then try below
var userid = $routeParams.id;
userTaskService
.getAllTasks()
.then((data) => {
vm.userTasks = data.filter(task => task.userId !== userid)
});