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); })*/