0

创建了名为movie的猫鼬模式,其对象属性引用了由multer-gridfs存储创建的另一个集合,但是当调用填充方法时,我在fileID上得到了null

架构是

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;

电影路线上的 post 和 get 方法是

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 但如果我删除填充返回我引用的字段的 objectsID

4

1 回答 1

0

在您的 MovieSchema 中,添加ref到 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;
于 2018-12-02T13:08:19.793 回答