benawad / graphql-mongo-server

55 stars 24 forks source link

Update in mongoose #1

Open Javadebi opened 5 years ago

Javadebi commented 5 years ago

Hi there tnx for all tutorials but i need help. Lets say you have user with name email and password. you want to set a mutation for updating the user. maybe only update the name and don't change others and sometimes update name and password. so how do you write the mutation? i wrote this: user.update({ name: args.name, email: args.email, password: args.password }) so if i only want to update name, both email and password become null. plz help

benawad commented 5 years ago

why not do user.update({ name: args.name })

Javadebi commented 5 years ago

what if the user also wants to update the email and password? what should i do?

Javadebi commented 5 years ago
Mutation: {
    createUser: async (parent, { name, email, password }) => {
        const user = new Users({ name, email, password });
        await user.save();
        return user;
    },
    deleteUser: async (parent, { id }) => {
        const user = await Users.findById(id);
        await user.deleteOne();
        return user;
    },
    updateUser: async (parent, args ) => {
        const user = await Users.findByIdAndUpdate(args.id, { $set: { 
        name: args.name, email: args.email, password: args.password }});
        return user;
    }
}
benawad commented 5 years ago

you could use if statements

const value = {}

if (args.email) {
   value.email = args.email
}

user.update(value)
Javadebi commented 5 years ago

tnx it works but how can you write a for statement for this i seen one in another language but dont know how to write it in graphql

benawad commented 5 years ago

do you mean a for loop over the args?

const values = {}
Object.entries(args).forEach(([key, value]) => {
if (value) {
values[key] = value
}
});
Javadebi commented 5 years ago

oh yes thanks you are the best :)

Javadebi commented 5 years ago

Hi again sry if i waste your time but i have a question. i want to write a backend for react native project for my university and i want to use apollo. Is it the right way im using apollo, mongoose, and express?

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const mongoose = require('mongoose');

const typeDefs = gql`
type Query {
    users: [User]
}
type User {
    id: String
    name: String
    email: String
    password: String
}
type Mutation {
    createUser(name: String!, email: String!, password: String!): User!
    deleteUser(id: ID!): User!
    updateUser(id: ID!, name: String, email: String, password: String): User!
}
`

const resolvers = {
Query: {
    users: () => {
        return Users.find();
    }
},
Mutation: {
    createUser: async (parent, { name, email, password }) => {
        const user = new Users({ name, email, password });
        await user.save();
        return user;
    },
    deleteUser: async (parent, { id }) => {
        const user = await Users.findById(id);
        await user.deleteOne();
        return user;
    },
    updateUser: async (parent, args ) => {
        const values = {};
        Object.entries(args).forEach(([key, value]) => {
            if (value) {
                values[key] = value;
            }
        });
        const user = await Users.findByIdAndUpdate(args.id, { $set: values }, { new: true }).exec()
            .catch((err) => {
                console.log(err)
            });
        return user;
    }
}
}

const app = express();

var dbUrl = 'mongodb://localhost:27017/test';
mongoose.connect(dbUrl);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, "DB connection error"));

const SERVER = new ApolloServer({
typeDefs,
resolvers,
playground: {
    endpoint: `http://localhost:3600/graphql`,
    settings: {
        'editor.theme': 'dark'
    }
}
});

SERVER.applyMiddleware({ app });

app.listen(3600, () => {
console.log(`Server ready at port 3600`);
});

const userSchema = new mongoose.Schema({
name: {
    type: String,
    required: true
},
email: {
    type: String,
    required: true,
    unique: true
},
password: {
    type: String,
    required: true
}
});

userSchema.set('toObjenct', { viruals: true });

var Users = mongoose.model('User', userSchema);
benawad commented 5 years ago

why are you getting an error of some kind?

Javadebi commented 5 years ago

no because i have seen people using GraphqlObjectType and those kind of thing i want to know if im doing right or wrong

benawad commented 5 years ago

your doing the Apollo way which is totally fine

Javadebi commented 5 years ago

tnx for the help. Do you know anywhere or anyone who has a complete course for Apollo?

benawad commented 5 years ago

I don't know of any off the top of my head that use mongo.