Mongoose簡單的連表查詢,Mongoose簡單

來源:互聯網
上載者:User

Mongoose簡單的連表查詢,Mongoose簡單

原文摘自我的前端部落格,歡迎大家來訪問

http://www.hacke2.cn

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

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

我們實驗的情境為一個班級有N多學生,先通過學生ID找到班級名稱(是不是被玩膩了?)

先來將Schema定義好

ClazzSchema :

var mongoose = require('mongoose')var ClazzSchema = new mongoose.Schema({clazzName:String})//其他方法省略..}module.exports = ClazzSchema

StudentSchema :

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使用populate

下面是Model

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


3個表連表查詢 教

select *,'查看' as sate from a
union all
select *,'下載' as state from b
union all
select *,'邀請' state from c

where 加三個表相關聯的關係

* 換成具體你要的欄位 但是個數 類型必須相同 實在不行可以null
 
資料庫連表查詢的問題

簡單:
select sendername=(select name from 表b WHERE SENDERID=ID),receivename=(select name from 表b WHERE RECEIVEID=ID),MailTitle from 表A
======
找到這個問題了。
這個查詢是最常見的查詢代碼字典的方法。
=====
而那個插入預存程序,是最常用的插入記錄並返回自動產生的程式碼的作法。
====
這兩個問題有聯絡嗎?看不出來。
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.