首先定义两个Schema,然后 model ;
DB.js
- // 分类
- let CategorieSchema = new mongoose.Schema({
- "name" : String,
- "img" : String,
- "date": Date
- });
- CategorieSchema.index({ "date": 1});
- // 商品
- let GoodsSchema = new mongoose.Schema({
- "name" : String,
- "img" : String,
- "date": Date,
- "count": Number,
- "content": String,
- "categoryId": {
- type: mongoose.Schema.ObjectId,
- ref: 'n_categorie' // 此处名称为let n_goods 的n_goods 区分大小写
- }
- });
- GoodsSchema.index({ "name": 1, "categoryId": 1});
- GoodsSchema.statics = {
- findCategoryByGoodsId:function (goodsId,callback) {
- return this.findOne({_id: goodsId}).populate('categoryId').exec(callback)
- }
- };
- //model
- let n_categorie = mongoose.model("n_categorie",CategorieSchema);
- let n_goods = mongoose.model("n_goods",GoodsSchema);
- exports.n_categorie = n_categorie;
- exports.n_goods = n_goods;
在需要的地方查询:
- const DB = require("../model/DB.js");
- DB.n_goods.findCategoryByGoodsId('5afc612ebe2db7194a3a703a',function (err ,category) {
- if (err) console.log(err)
- console.log(category.categoryId.name)
- })