简体   繁体   中英

Can't update document in MongoDB

So i'm trying to simply update a document in my database, i had no issues with getting data from the database. Here is my code:

const mongoose = require("mongoose");
    mongoose.connect("mongodb://localhost/mongo-exercises", {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });

//Creating Schema
const courseSchema = new mongoose.Schema({
  tags: [String],
  date: Date,
  name: String,
  author: String,
  isPublished: Boolean,
  price: Number,
});

//Creating model which returns a Class
const Course = mongoose.model("courses", courseSchema);


async function updateData(id) {
  try {
    const course = await Course.findById(id);

    course.isPublished = true;
    course.author = "another author";

    const resulti = await course.save();
    console.log(result);
  } catch (error) {
    console.log(error.message);
  }
}
updateData("5a68fdf95db93f6477053ddd");

Error i recieve:

Cannot set property 'isPublished' of null

Any pointers are appreciated thanks in advance:)

I found the solution, the database i was using had deprecated formatting for the id:s.

//In my database
_id: "5a68fdd7bee8ea64649c2777"

//How it should look
_id: ObjectID("5a68fdd7bee8ea64649c2777")

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