我想用一个动作删除两个对象。这两个对象都有共同的道具: gfs(file)-具有id属性 File(文字名称)-具有fileID属性,该属性从gfs(file)的id属性获取值。 这是函数,问题是删除不兼容的对象。
router.delete('/:id',auth,(req,res) => {
gfs.remove({ _id: req.params.id,root: 'files' },(err,gridStore) => {
if (err) {
return res.status(404).json({ err: err });
}
})
File.findOne(req.body.fileID)
.then(file => file.remove().then(() => res.json({ success: true })))
.catch(err => res.status(404).json({ success: false }));
});
gfs(和multer存储)在哪里:
conn.once('open',() => {
// Init stream
gfs = Grid(conn.db);
gfs.collection('files');
});
// // Create storage engine
const storage = new GridFsStorage({
db: conn,file: (req,file) => {
return new Promise((resolve,reject) => {
crypto.randomBytes(16,buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,bucketName: 'files'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
文件(后操作):
router.post('/',upload.single('file'),res) => {
const newFile = new File({
fileID: req.file.id,src: 'api/files/image/' + req.file.filename,altText: 'No image',caption: req.body.caption
// Grab the file id that was stored in the database by the storage engine as the reference to your file
})
newFile.save()
});
文件(模型):
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const FileSchema = new Schema({
fileID: {
type: Schema.Types.ObjectId
},src: {
type: String,},altText: {
type: String,caption: {
type: String,});
module.exports = File = mongoose.model('file',FileSchema);