node.js - Mongoose findById 查询不返回结果。对象始终为空。

标签 node.js mongodb mongoose mongodb-query

findById 不返回结果。每次我登录时 const course 对象都是 null。

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mongo-exercises', { useNewUrlParser: true });

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

const Course = mongoose.model('Course', courseSchema);

async function updateCourse(id){
        const course = await Course.findById(id);
        if(!course) return;

        course.isPublished = true;
        course.author = 'Another Author';

        const result = await course.save();
        console.log(result);
}

updateCourse('5a68fde3f09ad7646ddec17e');

最佳答案

问题已解决。我注意到,当我在 .findById() 更新之前导入集合时;对象的 id 被保存为字符串而不是 ObjectID

关于node.js - Mongoose findById 查询不返回结果。对象始终为空。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52702025/

相关文章:

javascript - 将对象从node.js发送到ejs,而不是[object Object]

javascript - 选择从数据上下文传递的 MongoDB 中的字段

javascript - 如何使用客户端的凭据从 Node 后端查询 firebase

node.js - 如何在 Node 中运行 PAC 代理脚本?

java - MongoDb和java dao实现

node.js - Mongoose 抑制警告选项

javascript - MissingSchemaError : Schema hasn't been registered for model

node.js - 在 Mongoose 模式中指定继承的通用模型

javascript - 是否可以在子模块的全局命名空间中保存要求(fs/http/等)?

mongodb - 默认情况下,32 位服务器没有启用日记功能。如果您想要持久性,请使用 --journal。 - 无法在 Windows 7 32 位上启动 mongo