Home > Software engineering >  Fill row with data MongoDB
Fill row with data MongoDB

Time:12-08

I'm using MongoDB and I want to fill the row 'userImg' that is in my User model. Below is my code:

User model:

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 (where I want to fill the userImg row of the User model):

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);
});

However, when executing this request, the row userImg is not updated in MongoDB: enter image description here

In this row I would like to put a URL of the image uploaded by the user.

CodePudding user response:

You should use the findOneAndUpdate method to update the userImg property.
Also, your should use async await since it returns a Promise.

Try to change your code like this:

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);
  });

CodePudding user response:

Are you saving somewhere the document after you set the new value for userImg property?

https://mongoosejs.com/docs/api.html#document_Document-save

  • Related