Node.js 为什么赢了';是否将文件内容保存在mongodb中
我使用的是express 2.5.8和mongoose 2.7.0。这是我的文档模式。它的集合是我想要存储与事务关联的文件的地方(特别是在内容字符串中): 下面是我的事务模式的一部分:Node.js 为什么赢了';是否将文件内容保存在mongodb中,node.js,express,mongoose,Node.js,Express,Mongoose,我使用的是express 2.5.8和mongoose 2.7.0。这是我的文档模式。它的集合是我想要存储与事务关联的文件的地方(特别是在内容字符串中): 下面是我的事务模式的一部分: var transactionSchema = new Schema({ txId : ObjectId, txStatus : {type: String, index: true, default: "started"}, documen
var transactionSchema = new Schema({
txId : ObjectId,
txStatus : {type: String, index: true, default: "started"},
documents : [{type: ObjectId, ref: 'Document'}]
});
我用来将文档保存到事务的express函数:
function uploadFile(req, res){
var file = req.files.file;
console.log(file.path);
if(file.type != 'application/pdf'){
res.render('./tx/application/uploadResult', {result: 'File must be pdf'});
} else if(file.size > 1024 * 1024) {
res.render('./tx/application/uploadResult', {result: 'File is too big'});
} else{
var document = new Document();
document.name = file.name;
document.type = file.type;
document.content = fs.readFile(file.path, function(err, data){
document.save(function(err, document){
if(err) throw err;
Transaction.findById(req.body.ltxId, function(err, tx){
tx.documents.push(document._id);
tx.save(function(err, tx){
res.render('./tx/application/uploadResult', {result: 'ok', fileId: document._id});
});
});
});
});
}
}
事务的创建没有任何问题。文档记录被创建,除了内容之外,一切都被设置好了
为什么内容没有设置好?fs.readFile将文件作为缓冲区返回,没有任何问题 变化:
document.content = fs.readFile(file.path, function(err, data){
致:
请记住,readFile是异步的,因此在调用回调之前,内容是不可用的(提示应该是您没有使用
数据参数)。而不是像@ebohlman建议的那样使用异步调用,
您还可以使用同步调用来获取文件内容
javascript
document.content=fs.readFileSync(file.path)
document.content = fs.readFile(file.path, function(err, data){
fs.readFile(file.path, function(err, data){
document.content = data;