猫鼬填充显示模式尚未注册模型填充

时间:2018-12-02 17:46:25

标签: mongoose mongoose-schema mongoose-populate

创建了名为“电影”的猫鼬模式,该对象具有对象属性,该对象引用了由multer-gridfs存储创建的另一个集合,但是当调用填充方法时,文件ID上为空

架构为

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返回为null,但如果删除填充,则返回我引用的字段的objectID。

1 个答案:

答案 0 :(得分:2)

将此行添加到movieSchema中

const Movies = mongoose.model('Movies', MovieSchema);
module.exports = { Movies };

并将其导入为

const { Movies } = require('../models/Movie');