我正在使用 MongoDB,我想填充用戶模型中的“userImg”行。下面是我的代碼:
用戶模型:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
(userSchema = new Schema(
{
unique_id: Number,
email: String,
username: String,
ageRange: String,
phone: String,
hobby: String,
fact: String,
password: String,
passwordConf: String,
userImg: String,
},
{
timestamps: true,
}
)),
(User = mongoose.model("User", userSchema));
module.exports = User;
Index.js(我想在其中填充 User 模型的 userImg 行):
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "file/");
},
filename: function(req, file, cb) {
cb(null, file.originalname);
},
});
var upload = multer({ storage: storage });
router.post("/upload", upload.single("file"), function(req, res, next) {
if (req.file === undefined) return res.send("you must select a file.");
const imgUrl = `http://localhost:3000/file/${req.file.originalname}`;
var userId = req.query.id;
console.log(userId);
const bla = User.findOne({ unique_id: userId }).populate({ path: "userImg", model: "User" })
bla.userImg = imgUrl;
return res.send("Uw afbeelding is succesvol geupload! " bla.userImg);
});
但是,在執行此請求時,MongoDB 中不會更新行 userImg:

在這一行中,我想放置用戶上傳的影像的 URL。
uj5u.com熱心網友回復:
您應該使用該findOneAndUpdate 方法來更新userImg屬性。
此外,您應該使用,async await 因為它回傳一個 Promise。
嘗試像這樣更改您的代碼:
router.post("/upload", upload.single("file"), async function(req, res, next) {
if (req.file === undefined) return res.send("you must select a file.");
const imgUrl = `http://localhost:3000/file/${req.file.originalname}`;
var userId = req.query.id;
const bla = await User.findOneAndUpdate(
{ unique_id: userId },
{ userImg: imgUrl },
{ new: true }
);
return res.send("Uw afbeelding is succesvol geupload! " bla.userImg);
});
uj5u.com熱心網友回復:
為 userImg 屬性設定新值后,是否將檔案保存在某處?
https://mongoosejs.com/docs/api.html#document_Document-save
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/376541.html
標籤:javascript 节点.js MongoDB 表达 猫鼬
