0

我正在尝试构建一个音乐应用程序,并且在为该应用程序(使用 express)工作的后端工作时,我面临着文档未保存在 mongo 集合中的奇怪问题。

我创建了一个用户提交表单数据的发布路径,其中包含歌曲的 mp3 文件和歌曲名称(稍后会有更多数据)。

我正在使用 multer 解析多部分表单数据。我可以使用 multer-gridfs-storage 将 mp3 文件保存到 mongoDB。我想将歌曲信息(例如名称、艺术家等)保存在不同的收藏中,这是该收藏的架构:

import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const SongsInfo = new Schema({
   name: {
     type: String,
     required: true,
   },
});

const Song = mongoose.model('Song', SongsInfo);
export default Song;

index.js 文件:

import Grid from 'gridfs-stream';
import GridFsStorage from 'multer-gridfs-storage';

const app = express();
const conn = mongoose.createConnection(mongoURI);

let gfs;

conn.once('open', () => {
  console.log('Connected to mongodb');
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection('songFiles');
});

// storage engine
const storage = new GridFsStorage({
  url: mongoURI,
  file: (req, file) => new Promise((resolve, reject) => {
    crypto.randomBytes(16, (err, buf) => {
      if (err) {
        return reject(err);
      }
      const filename = buf.toString('hex') + 
             path.extname(file.originalname);
      let fileInfo;

    fileInfo = {
      filename,
      bucketName: 'songFiles',
    };

      resolve(fileInfo);
    });
  }),
});
let upload;

middleWare(app);

app.post('/api/uploadSong', async (req, res) => {
  upload = multer({ storage }).any();

  upload(req, res, async (err) => {
    console.log('in');
    if (err) {
      // console.log(err);
      return res.end('Error uploading file.');
    }
    const { name } = req.body;
    // push a Song into songs collection
    const songInfo = new Song({
      name,
    });
    const si = await songInfo.save();    // (*)
    console.log(songInfo);
    res.json({
      songInfo: si,
      file: req.file,
    });
  });
});

在线 (*) 服务器只是冻结,直到请求超时。控制台上没有显示错误。不知道该怎么办:(

4

1 回答 1

0

我终于解决了这个问题!所以我所做的就是将模型放入 index.js 文件中,并在这里和那里改变了一些东西..

index.js

const app = express();
mongoose.connect(mongoURI); //(*)
const conn = mongoose.connection; // (*)

let gfs;

conn.once('open', () => {
  console.log('Connected to mongodb');
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection('songFiles');
});

// models
const Schema = mongoose.Schema; //(***)

const SongsInfo = new Schema({
  name: {
    type: String,
    required: true,
  },
});

const Song = mongoose.model('Song', SongsInfo);

// storage engine
const storage = new GridFsStorage({
  url: mongoURI,
  file: (req, file) => new Promise((resolve, reject) => {
    crypto.randomBytes(16, (err, buf) => {
      if (err) {
        return reject(err);
      }
      const filename = buf.toString('hex') + path.extname(file.originalname);
      let fileInfo;
      if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
        fileInfo = {
          filename,
          bucketName: 'imageFiles',
        };
      } else {
        fileInfo = {
          filename,
          bucketName: 'songFiles',
        };
      }
      resolve(fileInfo);
    });
  }),
});
let upload;

middleWare(app);

app.post('/api/uploadSong', async (req, res) => {
  upload = multer({ storage }).any();

  upload(req, res, async (err) => {
    console.log('in');
    if (err) {
      return res.end('Error uploading file.');
    }
    const { name } = req.body;
    // push a Song into songs collection
    const songInfo = new Song({
      name,
    });
    songInfo.save((er, song) => {
      if (!er) {
        res.send('err');
      } else {
        console.log(err, song);
        res.send('err');
      }
    });
  });
});

在第 (***) 行,我使用了初始化的相同 mongoose 实例。在上一个文件中,我再次从包中导入它...

于 2018-12-01T01:51:37.230 回答