我试图为用户上传图像时捕获文本生成的字符串(基于客户端/会话)。做从控制台db.collection.find();
当现在上传时捕获字符串并将其存储在mongoDB中
输出:
"_id" : ObjectId("590c67f472667e031fe80a9d"), "path" : "uploads/bicycle.jpg", "originalname" : "bicycle.jpg", "__v" : 0
在这里,我想有"imagelocation" : "N/A"
也。
该字符串基于上传图片时的用户位置。 我想将特定的字符串值连接到上面显示的图像对象ID。
App.js:
/image UPLOAD TO MONGODB
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
app.use(bodyParser.json());
//To get the access for the functions defined in imagefile.js class
var routes = require('./imagefile');
// connect to mongo,
mongoose.connect('mongodb://localhost:27017/gps');
app.use('/', routes);
// To get all the images/files stored in MongoDB
app.get('/images', function(req, res) {
routes.getImages(function(err, genres) {
if (err) {
throw err;
}
res.json(genres);
});
});
app.get('/images/:id', function(req, res) {
routes.getImageById(req.params.id, function(err, genres) {
if (err) {
throw err;
}
res.send(genres.path)
});
});
路径和ORIGINALNAME中被声明为我imagefile.js如下:
var imageSchema = mongoose.Schema({
path: {
type: String,
required: true,
trim: true
},
originalname: {
type: String,
required: true
},
imagelocation:{ // format for storing
type: String,
required: true
}
});
module.exports = mongoose.model('Image', stringClass);
var Image = module.exports = mongoose.model('files', stringClass);
router.getImages = function(callback, limit) {
Image.find(callback).limit(limit);
}
router.getImageById = function(id, callback) {
Image.findById(id, callback);
}
router.addImage = function(image, callback) {
Image.create(image, callback);
}
//multer
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/')
},
filename: function(req, file, cb) {
cb(null, file.originalname);
},
imagelocation: function(req,file,cb){
cb(null, $('#coordinates').innerHTML);
}
});
var upload = multer({
storage: storage
});
router.get('/', function(req, res, next) {
res.render('layouts/main.handlebars');
});
router.post('/', upload.any(), function(req, res, next) {
res.send(req.files);
var path = req.files[0].path;
var imageName = req.files[0].originalname;
var imagepath = {};
imagepath['path'] = path;
imagepath['originalname'] = imageName;
router.addImage(imagepath, function(err) {
});
});
module.exports = router;
HTML:
<p id="coordinates">String is generated here</p>
TL; DR - 怎么会我捕获一个字符串,并将其上传到我的MongoDB时,与图像一起发送?
整个项目可以在这里找到:https://github.com/joelfolkesson/myapp
文件中检查:
imagefile.js
app.js //(行204 - >)
嗯,是的,这是最初的想法,但是当我们尝试记录响应时返回“undefined”。你能否尝试用更全面的答案来实现你所写的内容?谢谢! – Joel
查看更新回答:) –
我已经尝试了一个小时,以使您的解决方案工作,但我根本不能。 :/我看不出这将如何将字符串存储在同一个db对象中。 – Joel