1

I'm trying to update an object that I have in MongoDB using Mongoose, but I am getting the error TypeError: course.save is not a function. I can create and find the 'course' objects just fine.
I've followed instructions in the course exactly and tried to troubleshoot but to no avail!
Any idea what's going on here?

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/playground', {
        useNewUrlParser: true
    })
    .then(() => console.log('Connected to MongoDB...'))
    .catch(err => console.error('Could not connect to MongoDB...', err));


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

const Course = mongoose.model('Courses', courseSchema);

async function createCourse() {
    const course = new Course({
        name: 'Course 1',
        author: 'Mosh',
        tags: ['angular', 'frontend'],
        isPublished: true
    });

    const result = await course.save(); // neccesarily async
    console.log(result);
}

// createCourse();

async function updateCourse(id) {
    const course = Course.findById(id);
    if (!course) return;
    course.isPublished = true;
    course.author = 'Another Author';    
    const result = await course.save();
    console.log(result);
}

updateCourse('5c1a528838633f2f80379061');

1 Answer 1

2

I Think it is because your find is asynchronous and you cannot using find method without a 'await' like this :

const course = await Course.findById(id);

Hope it helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually just realised this and was going to delete my question. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.