猫鼬模式虚拟属性日志 承诺 {<pending>} 而不是值?



我在我的用户模型上设置了一个虚拟属性来计算用户有多少帖子,但是当我在mocha测试中记录该值时,它记录Promise {}.

我不知道为什么我得到这个,因为在我的userSchema。虚拟路由,它将正确地记录post计数为" post计数:1">

我认为我返回值错误或什么?我如何返回值,使它可以读取??

谢谢!

Schema Virtual Property

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
})
<<p>测试代码/strong>
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) 

…因为虚函数("postCount")本身就是一个async函数

我认为问题在于您需要手动填充虚拟字段,因为默认情况下它们不会被填充(参见:https://mongoosejs.com/docs/populate.html#populate-virtuals)。

这个应该可以工作:

const sarah = await User.findOne({ username: "sarahsmith" }).populate('postCount');

最新更新