【问题标题】:mongoose findById using async await使用异步等待的猫鼬 findById
【发布时间】:2019-02-15 05:12:29
【问题描述】:

我正在尝试使用 async/await 更新集合。以下是我的代码:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mongo-exercises')
    .then(() => {
        console.log('Connected to MongoDB');
        UpdateCourse("5a68fdd7bee8ea64649c2777");
    })
    .catch(error => console.error('Could not connect to MongoDB : ' + error));

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

const Course = mongoose.model('course', courseSchema);
async function UpdateCourse(id) {
    console.log(`Inside Update Course. Finding ${id}`);
    const course = await Course.findById(id);
    console.log(`Course: ${course}`);
    if(!course)
        return;
    
    course.isPublished = true;
    course.author = 'Another Author';
    //course.set({isPublished: true, author: 'Another Author'});
    const saved = await course.save();    
    console.log(saved);
}

我在 mongo shell 中查询生成以下输出的集合:

在 UpdateCourse() 方法中,我将 null 作为课程的值。我确实在集合中有 id。谁能告诉我为什么在使用 async/await 时会出现此错误。

我尝试更改findById() -> findOne({_id: id})。同样的错误。我尝试更改findById() -> find({_id: id}) 在这里我得到UnhandledPromiseRejectionWarning: Unhandled promise rejection.。不明白为什么。

【问题讨论】:

  • 将您的代码包装在try/catch 中,这样您就可以看到实际的错误。见javascript.info/async-await#error-handling
  • 我做到了。使用 findById() 和 findOne() 相同的问题课程设置为 Null。但是通过 find 我得到 TypeError: course.save is not a function 错误。
  • 使用find 你会得到错误,因为它返回一个数组。为什么你这么确定你在集合中有 id?
  • 如果 course 为 null 您不会遇到任何错误。 try/catch 帮不了你
  • @Josh 我更新了我的问题,显示文档在集合中可用。你能解释一下如何通过它在 node.js 中的 id 来查找文档吗?我见过一些例子。即使是回调模式而不是 async/await 也会产生 null。

标签: node.js mongodb


【解决方案1】:

您要查找的文档中的_id 值是字符串,而不是ObjectId。因此,您需要更新架构以将 _id 定义为字符串;否则 Mongoose 会将您查询中的任何 _id 值转换为 ObjectId 的默认 _id 类型(导致查询与文档不匹配)。

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

说了这么多,您可能希望更新您的文档以使用 _id 的 ObjectId 值而不是 String,因为它更有效。

【讨论】:

  • 在添加 _id: String 之后,我可以检索该对象。谢谢你。一个问题。当我导入文档时,这些 _id 是自动创建的,我没有明确创建它们,所以它们应该是 ObjectId 而不是字符串,对吗? - 抱歉,.json 文件包含 _id 字段作为字符串。
  • 对,最佳实践是使用 ObjectIds 而不是 Strings。
  • 抱歉,我刚刚打开了 .json 文件,发现 _id 是字符串。感谢您的解释。 @Josh 感谢您的帮助。
猜你喜欢
  • 2018-04-13
  • 2018-08-30
  • 2019-05-10
  • 2020-10-16
  • 2018-06-11
  • 2020-08-01
  • 2018-08-09
  • 2019-12-12
  • 2021-09-12
相关资源
最近更新 更多