Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

javascript - How can I reference file.chunks on another schema that I created?

what I want to do is create a project that contains an name, description and an image (which is a reference to this schema). I've used multer so that I can store images in my database and everything works just fine up to this point. However when I try to show images on my page it won't show nothing.

Here's my code:

multer middleware:

const util = require('util');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');

var storage = new GridFsStorage({
url: "mongodb://localhost/teraApp",
options: {useNewUrlParse: true, useUnifiedTopology: true},
file: (req, file) =>{
    const match = ["image/png", "image/jpeg"];

    if(match.indexOf(file.mimetype) === -1){
        const filename = `${Date.now()}-TeraArch-${file.originalname}`;
        return filename;
    };
    return {
        bucketName: "photos",
        filename: `${Date.now()}-TeraArch-${file.originalname}`
       };
     }
  });

 const upload  = multer({storage: storage}).single('image');
 var uploadFileMiddleware = util.promisify(upload);
 module.exports = uploadFileMiddleware;

Route code:

router.post('/', upload, async (req, res) =>{
letname= req.body.name;
let desc = req.body.description;
const author ={
    id: req.user._id,
    username: req.user.username
};
const obj= {
    name: name,
    description: desc,
    author,
    img: req.file.id
};

    Project.create(obj, (err, project)=>{
        if(err){
            console.log(err);
        }else{
           res.redirect('/services');
            
        }
    });
  });

So my question is is there a way to reference files.chunks schema on my project schema so I can display the images, because this one is not working!?

projectSchema = new mongoose.Schema({
name: String,
description: String,
author: {
    id:{
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }
},
img: {
    id:{
        type: mongoose.Schema.Types.ObjectId,
        ref: "photos.chunks"
    }
}
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...