【问题标题】:mongoose findById or findone is not wotking猫鼬 findById 或 findone 不工作
【发布时间】:2019-09-10 05:57:19
【问题描述】:

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

我尝试过使用 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...

【问题讨论】:

  • 好吧,if (!course) return; 当然不会是一个错误,并且会解释为什么其余代码都没有发生日志记录。首先要检查的是您在请求中发送的id 确实存在。
  • 我建议展示您如何验证您认为文档确实存在。我的钱说你希望在名为 course 的集合中找到一个文档,而 mongoose 实际上正在寻找一个名为 courses 的集合。

标签: node.js mongodb mongoose


【解决方案1】:

你为什么不用findOneAndUpdate

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

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

【讨论】:

  • 不正确。您不需要exec(),因为您可以毫无问题地使用Course.findById(id).then(result => ...)。我所有的代码(还有很多)从不调用 exec。我只是await。如果您实际查看 mongoose 文档,则返回的对象是 Query,当然也有 then(),在这种情况下,这就是满足 Promise 的 API 规范所需的全部内容。 findOneAndUpdate()find .. change ..save 好,但是我的钱用于问题的另一个原因。
  • findOneAndUpdate 返回一个承诺。这里我使用了await 而不是.then
  • 为什么你会认为有区别?我指出exec() 没有区别。很容易理解。
【解决方案2】:

findById 返回一个查询而不是一个承诺。 让它执行查询并返回一个承诺使用:

await Course.findById(id).exec();

Mongoose findById

【讨论】:

  • 不正确。您不需要exec(),因为您可以毫无问题地使用Course.findById(id).then(result => ...)。我所有的代码(还有很多)从不调用 exec。我只是await。如果您实际查看 mongoose 文档,返回的对象是 Query,当然也有 then(),在这种情况下,这就是满足 Promise 的 API 规范所需的全部内容。
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

    好的,所以我导入了数据库,我认为这就是它无法正常工作的原因,但在创建新数据库后,代码工作正常......非常感谢所有努力提供帮助的人......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      相关资源
      最近更新 更多