首页 > 解决方案 > 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>} ??"
  })
})

标签: javascriptnode.jsmongoose

解决方案


事实证明,在读取这样的属性时我需要等待:

console.log(`SARAH POST COUNT`, await sarah.postCount) 

...因为 virtual("postCount") 本身就是一个异步函数


推荐阅读