Mongoose即便是簡單的表查詢

從我原來的博客尖,歡迎你們光臨javascript

http://www.hacke2.cnjava

像我這篇文章所說的基於Node.js + jade + Mongoose 模仿gokk.tv。當時中止開發是因爲我深深的感受到當時想錯了,應該用兩個Schema。而不是一個如下又有數組來存。這樣取數據是方便,當時分頁至關麻煩。不能使用原生提供的limit方法。mongodb

今天看到一本書上有講。嘗試了一把,記錄下來數組

咱們實驗的場景爲一個班級有N多學生。先經過學生ID找到班級名稱(是否是被玩膩了?)mongoose

先來將Schema定義好ui

ClazzSchema :this

var mongoose = require('mongoose')

var ClazzSchema = new mongoose.Schema({
	clazzName:String
})
//其它方法省略..
}

module.exports = ClazzSchema

StudentSchema :spa

var mongoose = require('mongoose')

var StudentSchema = new mongoose.Schema({
	name:String,
	clazzID : {
		type : mongoose.Schema.ObjectId,
		ref : 'Clazz'
	}
})

StudentSchema.statics = {
	findClazzNameByStudentId:function(studentId, callback){
			return this
				.findOne({_id : studentId}).populate('clazzID')
				.exec(callback)
		}
	//其它方法省略..
}

module.exports = StudentSchema

可以看到。主需要將ClazzID設爲ref到Clazz,依賴爲你創建Model時的名稱就可以了,要查詢Clzz使用populate3d

如下是Modelcode

var mongoose = require('mongoose')
var ClazzSchema = require('../schemas/clazzSchema')
var Clazz = mongoose.model('Clazz',ClazzSchema)


module.exports  = Clazz
var mongoose = require('mongoose')
var StudentSchema = require('../schemas/studentSchema')
var Student = mongoose.model('Student',StudentSchema)


module.exports  = Student

大同小異,着重看test.js

var mongoose = require('mongoose')
var Clazz = require('./models/clazzModel')
var Student = require('./models/studentModel')
//var db = mongoose.createConnection('localhost', 'gokk')
mongoose.connect('mongodb://localhost/test')

/*var clazz = new Clazz(
 {
 clazzName:'軟件2班'
 }
);

clazz.save(function (argument){
 console.log('true');
});*/

/*var student = new Student({
 name : 'hacke2',
 clazzID : '542b5fcc49df6e741d8d15f5'
})
student.save(function (err){
 console.log('true');
})*/

Student.findClazzNameByStudentId('542b600a683d59a80d4ee632', function (err, student){
	if(err) console.log(err);
	console.log(student.clazzID.clazzName);
})

以前加入了兩班級:軟件一班和軟件二班

咱們在新增hacke2時將classID設爲軟件2班的。查新hacke2時本身主動就會把關鍵的 Class查詢到

{ _id: 542b600a683d59a80d4ee632,
    name: 'hacke2',
    clazzID: { _id: 542b5fcc49df6e741d8d15f5, clazzName: '軟件2班', __v: 0 },
    __v: 0 }

end from http://www.hacke2.cn

相關文章
相關標籤/搜索