已知我们有两个数据model,一个是唱片信息数据Album,另一个是购入唱片所需的信息Purchase。
这是唱片model
// CREATE MODEL: Album
const { Schema, model } = require("mongoose");
const albumSchema = new Schema({
perfomer: {type: String},
title: {type: String},
cost: {type: Number}
});
const Album = model("Album", albumSchema);
// REMEMBER TO EXPORT YOUR MODEL:
module.exports = Album;
那如何在purchase的model中应用唱片的model呢?
// CREATE MODEL: Purchase
// CREATE MODEL: Album
const { Schema, model } = require("mongoose");
const Album = require("./album.model");
const PurchaseSchema = new Schema({
shippingAddress: {type: String},
album: {type: Schema.Types.ObjectId, ref: "Album"}
});
const Purchase = model("Purchase", PurchaseSchema);
// REMEMBER TO EXPORT YOUR MODEL:
module.exports = Purchase;
// REMEMBER TO EXPORT YOUR MODEL:
核心就是:
const Album = require("./album.model");//导入唱片模型
const PurchaseSchema = new Schema({
? album: {type: Schema.Types.ObjectId, ref: "Album"}//将唱片信息作为参考写入Purchase的数据中
});