首页 > 解决方案 > findByID() id 返回空值

问题描述

架构定义:

const coursesSchema = new mongoose.Schema({
    name: String,
    author: String,
    tags: [String],
    date: {
        type: Date,
        default: Date.now
    },
    isPublished: Boolean
});
const Courses = mongoose.model('Courses', coursesSchema);

在这里我连接到数据库模式

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongo-exercises').then(() => {
    console.log('mongoose connceted successfylly');
}).catch((err) => {
    console.log('mongoose didnt connected');
})

我正在尝试从 MongoDB 中获取记录。但它返回一个空值而不是对象

async function getCourses() {
  const course = await Courses.find();
  console.log(course);
} 

它运行良好,它正在从数据库中返回所有对象。

async function updateCourse(id) {
  const course = await Courses.findById({_id:id});
  console.log(course);
}

编辑:

这里我传递 ID 来获取 ID

updateCourse('5a68fe2142ae6a6482c4c9cb');

你可以检查我的数据库结构 即使我传递了正确的 ID

谁能帮我解决这个问题

标签: node.jsmongoose

解决方案


看一下findById文档,你只需要传递 id 作为参数,而不是匹配 id( {_id:id}) 的对象。

你的方法应该是这样的:

async function updateCourse(id) {
   const course = await Courses.findById(id);
   console.log(course);
}

推荐阅读