猫鼬findById或findone无法启动

时间:2019-04-20 05:55:45

标签: node.js mongodb mongoose

我可以查询我的收藏中的课程并列出它们,但无法更新

我尝试使用findone方法以及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');

没有收到任何错误...我的控制台仅显示已成功连接到mongodb ...

4 个答案:

答案 0 :(得分:0)

您为什么不使用findOneAndUpdate

await Course.findOneAndUpdate({_id:id},{$set:{isPublished:false,author:"Kalisha"}}).exec()

记住要使用.exec(),如果要返回更新的文档,请使用{new:true}

答案 1 :(得分:0)

# test if file descriptor 0 = standard input is connected to the terminal running_interactively () { [ -t 0 ]; } # if not running interactively, then redirect all output from this script to the black hole ! running_interactively && exec > /dev/null 2>&1 print_error_and_exit () { # if running interactively, then redirect all output from this function to standard error stream running_interactively && exec >&2 ... } 返回查询而不是诺言。 要让它执行查询并返回Promise,请使用:

findById

Mongoose findById

答案 2 :(得分:0)

这对我有用,请尝试一下,您的课程将会更新

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

答案 3 :(得分:0)

好的,所以我导入了数据库,我想这就是为什么它不起作用,但是在创建一个新数据库之后,代码可以正常工作....非常感谢所有努力提供帮助的人...