i have a file ./models/Image.js
const { Schema, model } = require('mongoose');
const imageSchema = new Schema({
title: {type: String},
description: {type: String},
author:{type:String},
filename: {type: String},
path: {type: String},
originalname: {type: String},
mimetype: {type: String},
size: { type: Number},
created_at: {type: Date, default: Date.now()},
authorname:{type:String}
});
module.exports = model('Image', imageSchema);
I have another file ./models/User.js
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name :{type:String,required : true} ,
email :{type : String,required : true} ,
password :{type : String,required : true} ,
date :{type : Date,default : Date.now}
});
const User= mongoose.model('User',UserSchema);
module.exports = User;
and a function inside routes/user
router.post('/upload', async (req, res) => {
const image = new Image();
image.title = req.body.title;
image.description = req.body.description;
image.filename = req.file.filename;
image.path = '/img/uploads/' req.file.filename;
image.originalname = req.file.originalname;
image.mimetype = req.file.mimetype;
image.size = req.file.size;
//image.authoremail= User.req.email; // what should i do here
await image.save();
res.redirect('/user/feed');
});
What i want is to put users name and email inside image schema so that i can compare it for later purposes for example in a page of dashboard user is only shown the picture he/she has uploaded but inside page 'feed' pictures of all users is displayed with there respective name
CodePudding user response:
In my opinion you should add user name and email field in the image schema. then set required = false, if it's not required for every case or you can add it without custom the schema by set strict = false in schema. it allow you to save or update the document in your case.
this is the answer that show how to set strict = false https://stackoverflow.com/a/50935227/15072782
CodePudding user response:
You can change the image Schema by using,reference document concept. So that you can just store user id.
const imageSchema = new Schema({
title: {type: String},
description: {type: String},
author:{type:String},
filename: {type: String},
path: {type: String},
originalname: {type: String},
mimetype: {type: String},
size: { type: Number},
created_at: {type: Date, default: Date.now()},
authorname: { // update here
type: Schema.Types.ObjectId,
ref: 'User'
}
});
module.exports = model('Image', imageSchema);
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name :{type:String,required : true} ,
email :{type : String,required : true} ,
password :{type : String,required : true} ,
date :{type : Date,default : Date.now}
});
const User= mongoose.model('User',UserSchema);
module.exports = User;