一、背景描述
现在有User表和Speak表,代码如下。我想通过Speak表的_userId联表查询User表获取个人信息。
//User表
const mongoose = require("mongoose")
const UserSchema = new mongoose.Schema({
username: {type: String},
introdution: String,
avatar: String,
gender:Number,
_create_date: {type: Date,default: Date.now},//创建时间
openid: String,
},{ _id: false })
UserSchema.plugin(autoIncrement.plugin,{
model: "User",
field: "_id",
startAt: 1000,
incrementBy: 1
})
const User = mongoose.model("User",UserSchema)
//Promise.promisifyAll来把一个模块所有的函数都变为async的
Promise.promisifyAll(User);
Promise.promisifyAll(User.prototype);
module.exports = User
//Speak表
const mongoose = require("mongoose")
const SpeakSchema = new mongoose.Schema({
_userId: {
type: Number,
ref: "User"
},
content: String,
imagesUrl: String,
likeNum: {default: 0, type: Number},
tag: String, //1:全部 2: 校园活动
isAnonymous: {default: false, type: Boolean},
isPass: {default: false, type: Boolean},
_create_date: {type: Date,default: Date.now},//创建时间
})
SpeakSchema.plugin(autoIncrement.plugin, {
model: "Speak",
field: "_speakId",
startAt: 1000,
incrementBy: 1
})
const Speak = mongoose.model("Speak", SpeakSchema)
Promise.promisifyAll(Speak);
Promise.promisifyAll(Speak.prototype);
module.exports = Speak
二、问题描述
上述的数据表结构是正确的,下面是一个不正确的表结构,关键在于User表的_id设置和_userId。
//User表
const mongoose = require("mongoose")
const UserSchema = new mongoose.Schema({
username: {type: String},
introdution: String,
avatar: String,
gender:Number,
_create_date: {type: Date,default: Date.now},//创建时间
openid: String,
_userId:Number
})
UserSchema.plugin(autoIncrement.plugin,{
model: "User",
field: "_id",
startAt: 1000,
incrementBy: 1
})
const User = mongoose.model("User",UserSchema)
//Promise.promisifyAll来把一个模块所有的函数都变为async的
Promise.promisifyAll(User);
Promise.promisifyAll(User.prototype);
module.exports = User
我想通过mongoose的populate函数来联表查询,可是出现了错误:
Speak.find().populate("_userId").exec(function(err,doc){
})
这时候我就懵了,怎么会使去找User表的_id呢?我以为是查询Speak表的_userId,然后到User表找_userId这字段来查找的。
三、解决问题
在这问题上我卡了很久,我很迷茫,因为根本不符合我的理解。我通过谷歌找了些相关文章对比一下,我也没发现我错在哪里。最后我选择去看官方文档,我发现了一句话,如下图,意思就是:有用ref这属性的字段的类型一定要对应被关联的表的_id的类型,我就纳闷了,为什么一定要与_id属性关联呢。。。。。,然后我改了一下User表的结构,果然可以联表查询了。
四、总结
1.要好好看仔细看官方文档,这次就是没留意这句话,我直接跳过没看,才导致出现这个问题。
附上一些有用的链接:
https://mongoosejs.com/docs/populate.html 官方文档
https://mongoose.shujuwajue.com/guide/population.html 中文文档