关于node.js:使用异步等待的mongoose findById

mongoose findById using async await

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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中查询集合,该集合产生以下输出:

enter image description here
在UpdateCourse()方法中,我当然将null作为值。 我的收藏中确实有ID。 谁能告诉我为什么在使用异步/等待时出现此错误。

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

enter image description here


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

1
2
3
4
5
6
7
8
9
const courseSchema = mongoose.Schema({
    _id: String,
    name: String,
    author: String,
    tags: [String],
    date: Date,
    isPublished: Boolean,
    price: Number
});

说了这么多,您可能想更新文档以将ObjectId值用于_id而不是String,因为它效率更高。