使用异步等待的猫鼬findById

时间:2018-09-10 18:15:32

标签: node.js mongodb

我正在尝试使用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中查询集合,产生以下输出:

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

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

enter image description here

1 个答案:

答案 0 :(得分:2)

您要查找的文档中的_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,因为这样更有效。