我有一個檔案 ./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);
我有另一個檔案 ./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;
和路由/用戶內部的功能
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');
});
我想要的是將用戶名和電子郵件放在影像架構中,以便我可以將其進行比較以備后用,例如在儀表板的頁面中用戶只顯示他/她上傳的圖片,但在所有用戶的頁面“提要”圖片內顯示有各自的名稱
uj5u.com熱心網友回復:
我認為您應該在影像架構中添加用戶名和電子郵件欄位。然后設定required = false,如果不是每種情況都需要它,或者您可以通過在schema中設定strict = false來添加它而不自定義架構。它允許您保存或更新您的案例中的檔案。
這是顯示如何設定strict = false https://stackoverflow.com/a/50935227/15072782的答案
uj5u.com熱心網友回復:
您可以使用參考檔案概念更改影像架構。這樣您就可以只存盤用戶 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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/379285.html
標籤:javascript 爪哇 节点.js MongoDB 猫鼬
上一篇:從tf1到tf2的幾個函式轉換
