I want to delete two objects with one action.
(我想用一个动作删除两个对象。)
Both objects have common props: gfs(file) - have id property File(name of literal) - have fileID property which take value from id property of gfs(file).(这两个对象都有共同的道具:gfs(file)-具有id属性File(文字名称)-具有fileID属性,该属性从gfs(file)的id属性获取值。)
Here's the function, the problem is that delete uncompatible objects.(这是函数,问题是删除不兼容的对象。)
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 }));
});
Where gfs(and multer storage):
(其中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, (err, 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 });
File(post action):
(文件(后操作):)
router.post('/', upload.single('file'), auth, (req, 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()
});
File(model):
(文件(型号):)
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);
ask by Victor translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…