
首先定义两个Schema,然后 model ;
DB.js
1. // 分类
2. let CategorieSchema = new mongoose.Schema({
3. "name" : String,
4. "img" : String,
5. "date": Date
6. });
7. CategorieSchema.index({ "date": 1});
8.
9. // 商品
10. let GoodsSchema = new mongoose.Schema({
11. "name" : String,
12. "img" : String,
13. "date": Date,
14. "count": Number,
15. "content": String,
16. "categoryId": {
17. type: mongoose.Schema.ObjectId,
18. ref: 'n_categorie' // 此处名称为let n_goods 的n_goods 区分大小写
19. }
20. });
21. GoodsSchema.index({ "name": 1, "categoryId": 1});
22. GoodsSchema.statics = {
23. findCategoryByGoodsId:function (goodsId,callback) {
24. return this.findOne({_id: goodsId}).populate('categoryId').exec(callback)
25. }
26. };
27.
28. //model
29. let n_categorie = mongoose.model("n_categorie",CategorieSchema);
30. let n_goods = mongoose.model("n_goods",GoodsSchema);
31.
32.
33. exports.n_categorie = n_categorie;
34. exports.n_goods = n_goods;
在需要的地方查询:
1. const DB = require("../model/DB.js");
2. DB.n_goods.findCategoryByGoodsId('5afc612ebe2db7194a3a703a',function (err ,category) {
3. if (err) console.log(err)
4. console.log(category.categoryId.name)
5. })