问题
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,
ref: 'fs' //created by multer gridfs storage
}
});
const Movie = mongoose.model('Movies', MovieSchema);
module.exports = Movie;
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
回答1:
add this line in your movieSchema
const Movies = mongoose.model('Movies', MovieSchema);
module.exports = { Movies };
and import it as
const { Movies } = require('../models/Movie');
来源:https://stackoverflow.com/questions/53582951/mongoose-populate-shows-schema-hasnt-been-registered-for-model-populate