javascript - Mongoose 架构虚拟属性日志 Promise {} 而不是价值?
问题描述
我正在我的用户模型上设置一个虚拟属性来计算用户有多少帖子,但是当我在我的 mocha 测试中记录该值时,它会记录Promise {}。
我不确定为什么会得到这个,因为在我的 userSchema.virtual 路由中,它会将帖子计数正确记录为“POST COUNT:1”
我想我返回的值是错误的还是什么?如何返回值以便可以读取?
谢谢!
架构虚拟属性
userSchema.virtual("postCount").get(async function () {
const Post = mongoose.model("Post")
const posts = await Post.find({ userId: this._id })
console.log(`POST COUNT: `, posts.length). // correctly logs "POST COUNT: 1"
return posts.length
})
测试代码
const Assert = require("assert")
const User = require("../src/models/user-model")
const Post = require("../src/models/post-model")
describe("finding user will auto populate postCount", () => {
beforeEach(async () => {
const sarah = new User({
username: "sarahsmith",
email: "test@sarah.com",
password: "sarahsarah",
})
await sarah.save()
const post1 = new Post({
caption: "test post 1",
userId: sarah._id,
mediaUrl: "amazon/s3.com/1",
})
await post1.save()
})
it("calculates user's post count ", async () => {
const sarah = await User.findOne({ username: "sarahsmith" }) // WORKS
console.log(`SARAH POST COUNT`, sarah.postCount) // logs "Promise {<pending>} ??"
})
})
解决方案
事实证明,在读取这样的属性时我需要等待:
console.log(`SARAH POST COUNT`, await sarah.postCount)
...因为 virtual("postCount") 本身就是一个异步函数
推荐阅读
- ruby-on-rails - 每当在生产中导致未初始化的常量错误
- postgresql - 使用带有 Alembic 迁移的逻辑分离将多个项目表迁移到一个数据库中的问题
- python - 如何用python识别日期中的结构?
- r - 为什么R在组合时将数字数据强制转换为字符?
- java - 在片段中单击按钮时,SetOnClickListener 不起作用
- javascript - Tinymce 内联编辑器不会在引导模式中显示菜单或工具栏
- javascript - 如何在 JavaScript 中的点击事件上重定向到某个 URL?
- docker - microk8s拉镜像,卡在ContainerCreating状态
- python - Leetcode中ListNode的Python逻辑
- regex - 不要在正则表达式中捕获可选的 html 标记