node.js - 使用异步等待的猫鼬 findById
问题描述
我正在尝试使用 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 中查询集合,产生以下输出:
在 UpdateCourse() 方法中,我将 null 作为课程的值。我确实在集合中有 id。谁能告诉我为什么在使用 async/await 时会出现此错误。
我试着改变findById() -> findOne({_id: id})
. 同样的错误。我试着findById() -> find({_id: id})
在这里改变我得到UnhandledPromiseRejectionWarning: Unhandled promise rejection.
。不明白为什么。
解决方案
_id
您要查找的文档中的值是字符串,而不是 ObjectId。因此,您需要更新架构以定义_id
为字符串;否则 Mongoose 会将查询中的任何 _id 值转换为默认的 _id 类型的 ObjectId(导致查询与文档不匹配)。
const courseSchema = mongoose.Schema({
_id: String,
name: String,
author: String,
tags: [String],
date: Date,
isPublished: Boolean,
price: Number
});
说了这么多,您可能希望更新您的文档以使用 ObjectId 值_id
而不是 String,因为它更有效。
推荐阅读
- java - Spring boot maven 项目每次都必须更新才能看到变化 ECLIPSE IDE
- javascript - 如何使用 Promise 返回函数返回的值?
- http - 在单个 HTTP GET 请求中检索集合资源的所有项目资源的 Last-Modified 标头
- powershell - 为什么 Win32_DiskPartition 不显示所有分区?
- python - 分类模型:如何查看每个分类的分数
- javascript - 如何从 fetch 中获取响应值而不是没有值的 promise?
- r - 如何创建标记连续旅程的分组变量?
- printing - 使用 DLL 文件从服务器本地 TCP/IP 打印机打印到多台打印机
- c# - 如何为 Xamarin Forms 创建具有延迟属性的异步绑定
- here-api - HERE 地图未渲染