猫鼬填充返回null

时间:2018-12-02 12:54:55

标签: mongoose mongoose-schema mongoose-populate multer-gridfs-storage

创建了一个名为movie的猫鼬模式,该对象的属性引用了multer-gridfs存储创建的另一个集合,但是当调用populate方法时,我的文件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,
    }
});


const Movie = mongoose.model('Movies', MovieSchema);

module.exports = Movie;

电影路线上的post and 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,但如果删除填充,则返回我引用的字段的objectID。

1 个答案:

答案 0 :(得分: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;