node.js - Mongoose - 引用另一个表中的字段
问题描述
我有两个表:Post
并且User
我想在 Post 表中引用用户名。
我可以引用 ID,但我还需要名称。
用户型号:
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
})
module.exports = mongoose.model("User", userSchema)
岗位型号:
const { ObjectId } = mongoose.Schema.Types
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
author: {
type: ObjectId,
ref: "User",
},
})
module.exports = mongoose.model("Post", postSchema)
他们在文档中说:
注意:ObjectId、Number、String 和 Buffer 可用作 refs。但是,除非您是高级用户并且有充分的理由这样做,否则您应该使用 ObjectId。
但是,我找不到有关如何执行此操作的示例。
解决方案
推荐阅读
- javascript - 我找不到我想要的 $search $text MongoDB
- ios - 如何查看 cocoapods 链接到的所有框架
- typescript - 是否可以强制执行更漂亮的样式作为 tslint 规则?
- python - 从字典中创建数据框
- jquery - jQuery 函数在所有具有相同类或以相同名称开头的 ID 的元素上运行
- android - 从程序向数据库添加数据。安卓
- css - 如何删除行开始/结束的左/右填充?
- react-native - loopback react sdk,TypeError: (0, _rxjs.from)(request).map is not a function while using find() method on model
- javascript - 在兄弟组件之间传递对象 - React js
- android - android:我再次进入活动后按钮不起作用