Mongoose implements DBRef to search for all subclass information, mongoosedbref
Product table
var Mongoose = require('mongoose');var Schema = Mongoose.Schema;var Product = new Schema({ image : { type : String }, description : { type : String }, price : { type : Number, require : true }, probability : { type : Number, require : true }, status :{ type : Number, require : true, default : 1 }, categoryId:{ type:String, require:true }, name : { type :String, require : true }},{ _id : true, autoIndex : true});module.exports = Mongoose.model('Product',Product);
Product Category Table
var Mongoose = require('mongoose');var Schema = Mongoose.Schema;var Category = new Schema({ child : [{ type : Schema.Types.ObjectId, ref : 'Product' }], name : { type : String, require : true }, description : { type : String, require : true }, image : { type : String, require : true }},{ _id : true, autoIndex : true});module.exports = Mongoose.model('Category',Category);
When we add a product, we insert the product id into the category.
Var product = new Product ({name: 'jurassic coffee ', image:'/3.jpg ', descript:' Still Okay ', price: 50.00, probability: 100, status: 1, categoryId: "552f76bd3e0b2dfca7989da3"}) product. save (function (err) {if (err) {console. log (err);} else {Category. find ({_ id: "552f76bd3e0b2dfca7989da3"}, function (err, result) {result [0]. child. push (product. _ id); result [0]. save (function (err) {console. log ('OK! ')})})}})
When searching for a category information, you can also find information that contains multiple commodities.
Category.find().populate('child').exec().then(function(result){ console.log(result); })
Let's take a look at the output:
[{_ Id: 552f76bd3e0b2dfca7989da3, image: '/1.jpg', description: 'Our coffee is from Brazil, safe and pollution-free, dry food, and instant food. ', name: 'coffee ', _ v: 7, child: [{_ id: 552f76a9bda-a1e8651bba8d, status: 1}, {_ id: 552f76ff61d8370ba8490ceb, name: 'tyrannosaurus coffee ', image:'/1.jpg ', price: 20, probability: 100, categoryId: '552f76bd3e0b2dfca7989da3 ', _ v: 0, status: 1}, {_ id: Taobao, name: 'sword tooth dragon coffee ', image: '/2.jpg', price: 15, probability: 100, categoryId: '552f76bd3e0b2dfca7989da3', _ v: 0, status: 1}, {_ id: Success, name: 'overlord coffee ', image:'/3.jpg ', price: 15, probability: 100, categoryId: '552f76bd3e0b2dfca7989da3', _ v: 0, status: 1 }, {_ id: Taobao, name: 'overlord coffee ', image:'/3.jpg ', price: 15, probability: 100, categoryId: '552f76bd3e0b2dfca7989da3', _ v: 0, status: 1}, {_ id: Taobao, name: 'yilong coffee ', image:'/3.jpg ', price: 25, probability: 100, categoryId: '552f76bd3e0b2dfca7989da3 ', _ v: 0, status: 1}, {_ id: 552f779cad597a3fa8365f63, name: 'chicken coffee ', image:'/3.jpg ', price: 250, probability: 100, categoryId: '552f76bd3e0b2dfca7989da3 ', _ v: 0, status: 1}, {_ id: Taobao, name: 'jurassic coffee', image: '/3.jpg', price: 50, probability: 100, categoryId: '552f76bd3e0b2dfca7989da3', _ v: 0, status: 1}]