我正在使用 mongoose 和 node.js 来查找文档并更新其属性,但每次我这样做时都会出现某种错误,无法登录控制台。这是 multer 的一些问题。谁能猜出 id 做错了什么?
我的架构:
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name : {
type: String,
required: true
},
email : {
type: String,
required: true
},
password : {
type: String,
required: true
},
details: {
type: Object,
},
profile_img: {
data: String,
contentType: String,
}
})
const User = mongoose.model('User',UserSchema);
module.exports = User
穆尔代码:
var fs = require('fs');
var path = require('path');
var multer = require('multer');
//store images in db
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads')
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString().replace(/:/g, '-')+ file.originalname);
}
});
const fileFilter = (req, file, cb) => {
// reject a file
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
fileFilter: fileFilter
});
路线:
router.post('/profile-chooser/developer/:method',upload.single('profile_photo'),ensureAuthenticated,(req,res) => {
//do db stuff
User.findOneAndUpdate({ "_id": mongoose.Types.ObjectId(req.user._id) },
{ "$set":
{
"details": {
"Some stuff": "update itttt"
},
"profile_img": {
"data": fs.readFileSync(path.resolve(__dirname, '../uploads/' + req.file.filename)),
"contentType": 'image/png'
}
}
})
.exec(function(err, user){
if(err) {
console.log(err);
res.status(500).send(err);
} else {
res.status(200).send(user);
}
});
})
我确信这是 multer 的一个问题,因为当我 fs.readFileSync(path.resolve(__dirname, ../uploads/ + req.file.filename))
将此行更改为字符串并且还upload.single(profile_photo)
神奇地将其删除时,它起作用了。
谁能帮帮我。
您的快速响应将不胜感激。
提前致谢。