Reputation: 39
created mongoose schema called movie with property of object reference to another collection of created by multer-gridfs storage but when called populate method i got null on fileID
The schema is
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MovieSchema = new Schema({
description: String,
category: String,
token: String,
fileID: {
type: mongoose.Schema.Types.ObjectId,
}
});
const Movie = mongoose.model('Movies', MovieSchema);
module.exports = Movie;
The post and get method on movie route is
const express = require('express');
const multer = require('multer');
const path = require('path')
const router = express.Router();
const Movie = require('../models/Movie');
const GridFsStorage = require('multer-gridfs-storage');
const storage = new GridFsStorage({
url: 'mongodb://127.0.0.1:27017/kannywoodtv-dev',
file: (req, file) => {
return {
filename: req.body.name + path.extname(file.originalname)
};
}
});
const upload = multer({
storage
});
router.post('/', upload.single('file'), (req, res) => {
console.log(req.file)
const movie = new Movie({
description: req.body.Description,
category: req.body.Category,
token: req.body.Description,
fileID: req.file.id
});
console.log(movie)
movie.save(function(err) {
if (err) {
console.log(err);
return;
}
res.json({
"success": "true"
});
});
});
router.get('/movies', (req, res) => {
Movie.find()
.populate('fileID')
.then(files => {
res.send(files)
}).catch(err => {
res.send(err)
})
})
module.exports = router;
fileID return when null when i called populate but return the objectsID of the field i reference if i remove populate
Upvotes: 0
Views: 367
Reputation: 13669
in your MovieSchema , add ref
to fileId :
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MovieSchema = new Schema({
description: String,
category: String,
token: String,
fileID: {
ref:'Files' // name of File Model schema
type:Schema.Types.ObjectId,
}
});
const Movie = mongoose.model('Movies', MovieSchema);
module.exports = Movie;
Upvotes: 0