var headSchema = new Schema({
typename: String,
headname: String,
status: { type: Number, default: 1 }
});
var Head = mongoose.model("heads", headSchema);
var mgmtSchema = new Schema({
headtype: String,
type: { type: Schema.Types.ObjectId, ref: "Head" },
datefrom: Date,
dateto: Date,
title: String,
amount: Number,
description: String,
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now },
status: Number
});
var HeadMgmt = mongoose.model("headmgmt", mgmtSchema);
HeadMgmt.find({})
.populate({ path: "type", select: "headname" })
.exec(function(err, result) {
console.log(result);
});
我有两个模式,也有外键引用。第二个模式具有一定的价值。我需要在一个html表中显示列表。如何从头模式打印头?
答案 0 :(得分:0)
在mgmtSchema
中,您需要将类型字段中的ref值从Head
更改为heads
,因为您使用heads
来设置Head模型是这样的:
var Head = mongoose.model("heads", headSchema);
所以您的mgmtSchema必须是这样的:
var mgmtSchema = new Schema({
headtype: String,
type: { type: Schema.Types.ObjectId, ref: "heads" },
datefrom: Date,
dateto: Date,
title: String,
amount: Number,
description: String,
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now },
status: Number
});
当前填充代码的结果将如下所示:
[
{
"_id": "5e13483dd62cd92e3c3e8dcd",
"headtype": "headtype",
"type": {
"_id": "5e1347671b0bd339e0521139",
"headname": "headname 1"
},
"title": "title",
"amount": 123,
"description": "description",
"created_at": "2020-01-06T14:46:21.906Z",
"updated_at": "2020-01-06T14:46:21.906Z",
"__v": 0
}
]