папка моделей:
Изображение js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ImgSchema = new Schema({
image_des: {
type: String,
required: true
},
date_capture: {
type: Date,
default: Date.now
},
user: { type: Schema.Types.ObjectId, ref: 'User' }
})
module.exports = Img = mongoose.model('img', ImgSchema);
Пользователь. js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
unique: true
},
register_date: {
type: Date,
default: Date.now
}
});
module.exports = User = mongoose.model('user', UserSchema)
В папке routes / api :
imgs. js:
const express = require('express');
const router = express.Router();
const auth = require('../../middleware/auth');
//Image Modal
const Img = require('../../models/Img');
//@route GET api/imgs
//@ desc Get all imgs
//@access Public
router.get('/', (req, res) => {
Img.find()
.sort({ date: -1})
.then(imgs => res.json(imgs))
});
//@route POST api/items
//@ desc Create a item
//@access Private
router.post('/', auth, (req, res) => {
const newImg = new Img({
image_des: req.body.image_des
});
newImg.save().then(img => res.json(img));
});
module.exports = router;
пользователей. js:
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const config = require("config");
const jwt = require("jsonwebtoken");
//User Model
const Item = require("../../models/User");
//@route POST api/users
//@ desc Register new user
//@access Public
router.post("/", (req, res) => {
const { name, email, password } = req.body;
//Simple Validation
if (!name || !email || !password) {
return res.status(400).json({ msg: "Please enter all field" });
}
//Check for existing user
User.findOne({ email }).then(user => {
if (user) return res.status(400).json({ msg: "User already exists" });
const newUser = new User({
name,
email,
password
});
//Create salt & hash
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save().then(user => {
jwt.sign(
{ id: user.id },
config.get("jwtSecret"),
{ expiresIn: 3600 },
(err, token) => {
if (err) throw err;
res.json({
token,
user: {
id: user.id,
name: user.name,
email: user.email
}
});
}
);
});
});
});
});
});
module.exports = router;
imgActions. js:
import axios from 'axios';
import { GET_IMAGE, ADD_IMAGE, IMAGES_LOADING } from './types';
import { tokenConfig } from './authActions';
import { returnErrors} from './errorActions';
export const getImage = () => dispatch => {
dispatch(setImagesLoading());
axios.get('/api/imgs').then(res =>
dispatch({
type: GET_IMAGE,
payload: res.data
}))
.catch(err =>
dispatch(returnErrors(err.response.data, err.response.status))
);
};
export const addImage = img => (dispatch, getState) => {
axios
.post('./api/imgs', img, tokenConfig(getState))
.then(res =>
dispatch({
type: ADD_IMAGE,
payload: res.data
})
).catch(err =>
dispatch(returnErrors(err.response.data, err.response.status))
);
};
export const setImagesLoading = () => {
return {
type: IMAGES_LOADING
};
};
authActions. js:
import axios from 'axios';
import { returnErrors } from './errorActions'
import {
USER_LOADED,
USER_LOADING,
AUTH_ERROR,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT_SUCCESS,
REGISTER_SUCCESS,
REGISTER_FAIL
} from "../actions/types";
// Check token & load user
export const loadUser = () => (dispatch, getState) => {
// User loading
dispatch({ type: USER_LOADING });
axios.get('/api/auth/user', tokenConfig(getState))
.then(res => dispatch({
type: USER_LOADED,
payload: res.data
}))
.catch(err => {
dispatch(returnErrors(err.response.data, err.response.status));
dispatch({
type: AUTH_ERROR
});
});
};
//Register User
export const register = ({ name, email, password }) => dispatch => {
//Headers
const config = {
headers: {
'Content-Type': 'application/json'
}
}
//Request body
const body = JSON.stringify({name, email, password});
axios.post('/api/users', body, config)
.then(res => dispatch({
type: REGISTER_SUCCESS,
payload: res.data
}))
.catch(err => {
dispatch(returnErrors(err.response.data, err.response.status, 'REGISTER_FAIL'));
dispatch({
type: REGISTER_FAIL
});
});
};
//Login User
export const login = ({ email, password }) => dispatch => {
//Headers
const config = {
headers: {
'Content-Type': 'application/json'
}
}
//Request body
const body = JSON.stringify({email, password});
axios.post('/api/auth', body, config)
.then(res => dispatch({
type: LOGIN_SUCCESS,
payload: res.data
}))
.catch(err => {
dispatch(returnErrors(err.response.data, err.response.status, 'LOGIN_FAIL'));
dispatch({
type: LOGIN_FAIL
});
});
};
// Logout User
export const logout = () => {
return {
type: LOGOUT_SUCCESS
};
};
// Setup config/headers and token
export const tokenConfig = getState => {
//Get token from localstorage
const token = getState().auth.token;
//Headers
const config = {
headers: {
"Content-type": "application/json"
}
};
//If token, add to headers
if(token) {
config.headers['x-auth-token'] = token;
}
return config;
}
Итак, моя проблема в том, как связать изображения с пользователем. Например, изображение будет хранить user_id или user_email. В настоящее время я использую стек MERN, я следовал руководству Traversy Media. Если кто-то сможет посмотреть на это и помочь, будет здорово. Спасибо!