0

i work by NODE.JS by express, and mongo , mongodb, and execute CRUD by them. i can do GET and CREATE new document, BUT i can't execute DELETE & UPDATE using ID by same utilities.

note: this id, is valid and exist in my database. i checked this.

when i try this code, i receive this message in console:

connected to MONGOdb...

null

my DELETE code is in belove:

const mymongoose = require('mongoose');
mymongoose.connect('mongodb://localhost/mongo-exercises')
.then(() => console.log('connected to MONGOdb...'))
.catch(er => console.error('could not connect to mongodb', er));

const courseSchema = new mymongoose.Schema({
name: String,
author: String,
tags: [String],
date: {type: Date, default: Date.now},
isPublished: Boolean,
price: Number
});

const Course = mymongoose.model('Course', courseSchema);

//Remove code:
async function removeCourse(id) {
const course = await Course.findByIdAndRemove(id);
console.log(course);
}
removeCourse('5a68ff090c553064a218a547');
hamed
  • 39
  • 1
  • 7

1 Answers1

0

Based on the code removeCourse('5a68ff090c553064a218a547'); The Id is being passed as a string instead of a mongodb object Id.

Try formatting / converting the string Id you have to an object Id like this.

mongoose.Types.ObjectId('5a68ff090c553064a218a547');

Related question And other available answers for this.

sigrid
  • 11
  • 2