node.js - 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');
谁能帮我解决这个问题
解决方案
看一下findById
文档,你只需要传递 id 作为参数,而不是匹配 id( {_id:id}
) 的对象。
你的方法应该是这样的:
async function updateCourse(id) {
const course = await Courses.findById(id);
console.log(course);
}
推荐阅读
- angular - Angular:如何构建环境不可知论者?
- python - 有没有办法一次展平多个列表
- javascript - 将字符串拆分为具有 1-3 个单词的字符串数组,具体取决于长度
- c++ - 线程不执行函数
- r - 对 Mac 和 Windows 中 r 中 awk 的 ebd 文件路径的连接进行故障排除
- hibernate - “在刷新之前保存瞬态实例”错误
- c - 查找字长统计的程序
- reactjs - 当我传递到另一个屏幕时如何停止 Firebase 侦听器?
- c# - 为什么我有错误“'SQLiteCommand'不包含'Parameters'的定义”?
- c# - c# if not null then assign value的简写