标签:信息
产品表
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);
产品分类表
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);
我们在每添加一个商品的时候把该商品的id插入category中
var product = new Product({
name : ‘侏罗纪咖啡‘,
image : ‘/3.jpg‘,
descript : ‘还算可以‘,
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!‘)
})
})
}
})
在查找一个分类信息时同时找到它对应的多有商品的信息
Category.find().populate(‘child‘).exec().then(function(result){
console.log(result);
})
我们来看下输出结果:
[ { _id: 552f76bd3e0b2dfca7989da3,
image: ‘/1.jpg‘,
description: ‘我们的咖啡来自巴西,安全无公害,干吃,泡着吃都行‘,
name: ‘咖啡‘,
__v: 7,
child:
[ { _id: 552f76a9b396a1e8651bba8d, status: 1 },
{ _id: 552f76ff61d8370ba8490ceb,
name: ‘暴龙咖啡‘,
image: ‘/1.jpg‘,
price: 20,
probability: 100,
categoryId: ‘552f76bd3e0b2dfca7989da3‘,
__v: 0,
status: 1 },
{ _id: 552f773a12831318a8d51ce4,
name: ‘剑齿龙咖啡‘,
image: ‘/2.jpg‘,
price: 15,
probability: 100,
categoryId: ‘552f76bd3e0b2dfca7989da3‘,
__v: 0,
status: 1 },
{ _id: 552f776a87443f28a8e66931,
name: ‘霸王龙咖啡‘,
image: ‘/3.jpg‘,
price: 15,
probability: 100,
categoryId: ‘552f76bd3e0b2dfca7989da3‘,
__v: 0,
status: 1 },
{ _id: 552f777f87443f28a8e66932,
name: ‘霸王龙咖啡‘,
image: ‘/3.jpg‘,
price: 15,
probability: 100,
categoryId: ‘552f76bd3e0b2dfca7989da3‘,
__v: 0,
status: 1 },
{ _id: 552f77846a87b934a8a45cfa,
name: ‘翼龙咖啡‘,
image: ‘/3.jpg‘,
price: 25,
probability: 100,
categoryId: ‘552f76bd3e0b2dfca7989da3‘,
__v: 0,
status: 1 },
{ _id: 552f779cad597a3fa8365f63,
name: ‘小鸡咖啡‘,
image: ‘/3.jpg‘,
price: 250,
probability: 100,
categoryId: ‘552f76bd3e0b2dfca7989da3‘,
__v: 0,
status: 1 },
{ _id: 552f77ac294f5d4ba8006b27,
name: ‘侏罗纪咖啡‘,
image: ‘/3.jpg‘,
price: 50,
probability: 100,
categoryId: ‘552f76bd3e0b2dfca7989da3‘,
__v: 0,
status: 1 } ] } ]
标签:信息
原文地址:http://blog.csdn.net/bugall/article/details/45082245