Reputation: 114
How do I save some file in mongoose?
For example I have a route for POST
method /
, and GET
method /
.
Posting to /
should save sent file to MongoDB database (mongoose), and Getting /
should send the saved file. If file was an image how do I send it to client as image? (Is it a good practice to save raw file from user, or should I save them in mongodb - if so: how?).
Upvotes: 0
Views: 913
Reputation:
First it's clear that you should have schema for your mongoDB
.
You can have it in SCHEMA.js
file like this:
module.exports = {
model: function(Schema) {
return new Schema({
_id: { type: String, index: true, unique: true },
updateDate: { type: Date, default: Date.now },
data: String
})
}
}
then you have for your requests you can do as below:
router.post('/', function(req, res){
var data = req.body.data;
SCHEMA = require('/YOUR/SCHEMA/PATH').SCHEMA;
SCHEMA.update({
_id: data.id
}, {
data: data
}, {
upsert: true
}, function (err) {
if (err) {console.error('subs-on-userapps> failed update token, err=',err);}
});
})
In above part you get data form request and then insert it to you mongoDB.
** .update
first search for you data in first part and with upsert:true
option insert data if not exist before.
For have access to your data you have other route with Get
method so:
router.get('/', function(req, res){
SCHEMA.findOne({QUERY})
.execQ()
.then(function(result) {
res.json({result: result})
});
})
Upvotes: 2