【发布时间】:2017-11-15 07:49:18
【问题描述】:
嘿,我对 Javascript 和 Node 还很陌生,但我遇到了一个困扰我一段时间的问题。
我有一个 User 模型和一个 Image 模型,我正在使用 Multer 上传一组图像,尝试遍历这个数组,为每个模型创建一个新的 Image 模型,然后取消移动该 Image进入我用户的照片。我已将 Multer 设置为成功填充 req.files。这是代码。
router.post("/users/:user/photos/upload", middle.isLoggedIn, upload.array("photos", 4), function(req, res) {
User.findById(req.params.user, function(err, foundUser) {
for(var i = 0, len = req.files.length; i < len; i++) {
Image.create(req.files[i], function(err, newImage) {
if(err) {
return console.log(err.message);
}
newImage.human = foundUser;
newImage.save();
console.log(newImage);
foundUser.photos.unshift(newImage);
foundUser.save();
});
}
console.log(foundUser);
});
});
console.log(foundUser); 似乎在console.log(newImage); 之前执行和打印
用户模型
var mongoose = require("mongoose"),
passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String,
firstName: String,
lastName: String,
city: String,
photos: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Image"
}
]
});
HumanSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
图像模型
var mongoose = require("mongoose");
var ImageSchema = new mongoose.Schema({
fieldname: String,
originalname: String,
mimetype: String,
filename: String,
destination: String,
size: Number,
path: String,
human: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Human"
}
}
});
module.exports = mongoose.model("Image", ImageSchema);
这是我的第一个 stackoverflow 问题,如果我没有发布足够的代码,请告诉我。
我认为这与 Image.create() 是异步的有关,我仍在尝试了解有关此和承诺的更多信息,但我仍然不完全理解它与我的代码的相关性。
【问题讨论】:
-
我看不到您的代码
console.log(req.user);出现在哪里。你的意思是console.log(foundUser);? -
是的@dave 抱歉,已编辑原帖
标签: javascript node.js mongodb mongoose mongoose-schema