mongodb 集合间不能联表查找的。ms sql中有join这样的语法。
当然mongodb 也可以实现:
先放代码:
var mongoose=require('mongoose');
var Schema = mongoose.Schema;
ObjectId = Schema.ObjectId;
var url = 'mongodb://localhost:27017/nodejs';
var conn=mongoose.connect(url);
var todo_schema=new Schema({
id:ObjectId,
name:String,
age:{type:Number,default:0},
store:[ {
type: ObjectId,
ref: 'store'
}],
meta:{
createAt:{
type:Date,default:Date.now()
},updateAt:{
type:Date,default:Date.now()
}
}
})
var todo=conn.model('todo',todo_schema)
var store_schema=new Schema({
id:ObjectId,
school:String,
con:String,
text:String
})
var store=conn.model('store',store_schema)
todo.find({_id:'56d954adc50990813629a16e'}).populate('store').exec(function(err,doc){
console.log(doc)
})
//在查看后用populate("") 会把联表的id 转换为对象。
todo.find({_id:'56d95ded648b65e99619fc75'}).populate('store').exec(function(err,doc){
console.log('------------56d95ded648b65e99619fc75')
console.log(doc);
})
//Id 查找记录 添加store 并save
/*todo.findById('56d94968adc802e8b7a3fbc3').exec(function(err,doc){
console.log('----------------')
doc.store.push('56d9492223a47fb89cffa5db')
console.log(doc.store)
doc.save(function(err,doc){
console.log(doc)
})
})*/
//create
/*var a=new todo({name:'todo',age:120,store:['56d9492223a47fb89cffa5db']});
a.save(function(err,doc){
console.log('--------------save')
console.log(doc);
})*/
使用:
在创建Schema 时定义联合表和id
store:[ {
type: ObjectId,
ref: 'store' //指定的集合名
}]
type: ObjectId,
ref: 'store' //指定的集合名
}]
这里用数组对象最好,如果直接是对象,表现出来就是一对一的关系 。
如果是数据就是一对多的关系 。
查找:
在find().populate('sotre')
默认的find()会显示store里的id 而不是把id转换成id的对象。
加上populate就可以了。
结果就是联合表的对象。
创建:
在创建时为store:['xx']就可
添加:
先用findById查找对象,
用doc.store.push()添加id
doc.save保存就可以了。
本文介绍如何在MongoDB中实现集合间的联表查找,包括创建Schema定义联合表、查询方式、创建与添加数据的方法。
2824

被折叠的 条评论
为什么被折叠?



