简体   繁体   中英

JavaScript - Express - MongoDb - Mongoose findOneAndUpdate is returning undefined

So I'm trying to update an item within my mongodb database but it's not working and the error keyword is being set to undefined. I'm probably doing something very wrong but here's the update function:

router.post("/file/:id/edit", (req, res) => {
  var id = req.params.id;
  File.findOneAndUpdate( {"_id": id} , req.body, (err) => {
  if (err) return res.json({ success: false, error: err });
    return res.json({ success: true });
  });
});

The function that calls it:

export function updateFile(file) {
  var objIdToUpdate = file["id"];
  var myUpdate = axios.post("http://localhost:3001/api/file/:" + objIdToUpdate + "/edit", {
        title: file.title,
        author: file.author,
        dateCreated: file.dateC,
        dateModified: file.dateModified,
        size: file.size,
        type: file.type,
        tags: file.tags
  });
  return myUpdate;
}

My schema:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const FileSchema = new Schema(
  {
    title: String,
    author: String,
    dateCreated: String,
    dateModified: String,
    size: String,
    type: String,
    tags: []
  },
  { timestamps: true }
);

module.exports = mongoose.model("File", FileSchema, "files");

When I try to print the "err" keyword it's simply undefined. Why is this not working to modify values in my database, what's gone wrong?

In your callback function of findOneAndUpdate, err always have a value in it, its better if you use the then and catch with promises like this:

File.findOneAndUpdate({ "_id":  req.params.id}, { req.body },{returnNewDocument: true})
    .then((resp) => { res.send(resp) })
    .catch((err) => { res.send(err) });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM