首页 > 解决方案 > mongoose findById or findone is not wotking

问题描述

I am able to query courses in my collection and list them but am failing to update them

I have tried using the findone method as well as findById

const mongoose = require('mongoose');

 mongoose.connect('mongodb://localhost/mongo-exercises', {useNewUrlParser: true})
    .then(() => console.log(' Successfuly connected to mongodb...'))
    .catch(err => console.error('Ooops! something went wrong', err));

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

const Course = mong.model('Course', courseSchema);
  async function updateCourse(id) {
    const course = await Course.findById(id);

    if (!course) return;

    course.isPublished = false;
    course.author = 'Kalisha';

    // course.set({
    //     isPublished: true,
    //     author: 'Kalisha Malama'
    // });

      const  result = await course.save();
      console.log(result);
  }
updateCourse('5a68fe2142ae6a6482c4c9cb');

Am not getting any error...my console just shows successfully connected to mongodb...

标签: node.jsmongodbmongoose

解决方案


这对我有用试试这个,你的课程将被更新

   async function updateCourse(id) {
        await Course.find({
    _id: id
    })
    .then(doc => {
    doc.isPublished = false;
    doc.author = 'Kalisha';
    doc.save();
    })
    .catch(err => {
    console.log(err);
    })
      }

推荐阅读