摘要:實(shí)現(xiàn)代碼最近在做一個(gè)項(xiàng)目涉及到的關(guān)聯(lián)查詢(xún)等等,之前做的,比較多,而用的都是比較簡(jiǎn)單的存儲(chǔ)數(shù)據(jù),簡(jiǎn)單查詢(xún)等等。
mongoose-ref
實(shí)現(xiàn)代碼github
最近在做一個(gè)項(xiàng)目涉及到mongoose的關(guān)聯(lián)查詢(xún)等等,之前做的mysql,postgresql比較多,而mongoose用的都是比較簡(jiǎn)單的存儲(chǔ)數(shù)據(jù),簡(jiǎn)單查詢(xún)等等。
剛開(kāi)始涉及ref還是有點(diǎn)小暈的,查詢(xún)了相關(guān)資源,也可以模模糊糊做出來(lái),但是會(huì)有各種報(bào)錯(cuò)。痛下決心研究透徹點(diǎn),晚上熬夜到2點(diǎn)終于有點(diǎn)小眉目了。
1. 首先建立了一個(gè)mongoose-ref項(xiàng)目node v8.5.0
mongodb
結(jié)合一個(gè)接口理解
結(jié)合promise-async-await
一般采用mvc模式,本文就直接在express里直接寫(xiě)了
直接使用了express -e mongoose-ref
2.在routes/index里連接mongodb數(shù)據(jù)庫(kù)const mongoose = require("mongoose"); mongoose.connect("mongodb://localhost:27017/ref");3.建立4個(gè)模型,用戶:User,城市:City,省份:State,國(guó)家:Country
同時(shí)建立關(guān)聯(lián)user->city->state->country
const Schema = mongoose.Schema; const ObjectId = Schema.Types.ObjectId; const UserSchema = new Schema({ username: { type: String }, userpwd: { type: String }, userage: { type: Number }, city: { type: Schema.Types.ObjectId, ref: "City" }, }); const CitySchema = new Schema({ name: { type: String }, state: { type: Schema.Types.ObjectId, ref: "State" } }); const StateSchema = new Schema({ name: { type: String }, country: { type: Schema.Types.ObjectId, ref: "Country" } }); const CountrySchema = new Schema({ name: { type: String } }); const User = mongoose.model("User", UserSchema); const City = mongoose.model("City", CitySchema); const State = mongoose.model("State", StateSchema); const Country = mongoose.model("Country", CountrySchema);4.主要采用promise-async-async進(jìn)行邏輯處理 首先創(chuàng)建一個(gè)user_getCountryList函數(shù),如下代碼
const user_getCountryList = async function (req, res) { console.log("/v1/ref start -->" + JSON.stringify(req.body)); try { const respondData = { status: res.statusCode, data: {}, error: {} }; const username = req.body.username; const userpwd = req.body.userpwd; const userage = req.body.userage; const usercityname = req.body.usercityname; const userstatename = req.body.userstatename; const usercountryname = req.body.usercountryname; const userInfoCountry = await findUserCountry({ name: usercountryname }, usercountryname);//查看國(guó)家 const userInfoState = await findUserState({ name: userstatename }, userstatename);//查看州 const userInfoCity = await findUserCity({ name: usercityname }, usercityname);//查看城市 const userInfo = await findUser({ username: username, }, username,userpwd,userage);//查看用戶信息 const updateInfoUser = await updateUser({ _id: userInfo },userInfoCity);//更新用戶信息 const updateInfoCity = await updateCity({ _id: userInfoCity }, userInfoState);//更新城市信息 const updateInfoState = await updateState({ _id: userInfoState }, userInfoCountry);//更新州信息 return res.json(respondData); } catch (error) { //錯(cuò)誤處理 console.log("userCity error -->" + JSON.stringify(error)); respondData.error = error; return res.json(respondData); } }
首先查看傳入的國(guó)家在country中有沒(méi)有,加入有,返回_id,沒(méi)有就創(chuàng)建傳入的國(guó)家名,并返回_id,查看findUserCountry函數(shù)對(duì)應(yīng)的邏輯
const findUserCountry = async function (cnd, country) { console.log("findUserCountry start --> " + JSON.stringify(cnd)); return new Promise(function (resolve, reject) { Country.findOne(cnd, function (error, data) { console.log("findUserCountry findOne data --> " + JSON.stringify(data)); if (error) { return reject(error); } if (data) { return resolve(data._id); } else { const userCountry = new Country({ name: country }); userCountry.save(function (err, data) { if (err) { console.log("userCountry.save err-->" + JSON.stringify(err)); return reject(err); } console.log("userCountry-->" + JSON.stringify(data)); return resolve(data._id); }); } }); }) }
同理傳入的州,城市,用戶信息以同樣的方式返回_id
接下來(lái)就要進(jìn)行關(guān)聯(lián)user->city->state->country通俗的說(shuō)就是在User表中city保存City表中所需要的_id;也就是之前返回的_id這時(shí)就可以用到,可以參考updateUser函數(shù)
const updateUser = async function (cnd, cityid) { console.log("updateUser start --> " + JSON.stringify(cnd)); return new Promise(function (resolve, reject) { User.update(cnd, { $set: { city: cityid } }, function (error, data) { console.log("updateUser findOne data --> " + JSON.stringify(data)); if (error) { return reject(error); } return resolve(data); }); }) }
可以使用postman模擬數(shù)據(jù),如圖:
這時(shí)就把City對(duì)應(yīng)的_id寫(xiě)進(jìn)了User表中,可以查看表,如圖:
同理user->city->state->country數(shù)據(jù)都可以寫(xiě)進(jìn)不同的表中。
當(dāng)傳入username 時(shí),使用populate關(guān)聯(lián)查詢(xún),可以查詢(xún)出這個(gè)人的所以信息
User.find({ username: user_name }) .populate("city") .exec(function (err, docs) { City.find({ _id: docs[0].city._id }) .populate("state") .exec(function (err, doc) { State.find({ _id: doc[0].state._id }) .populate("country") .exec(function (err, result) { const userInfo = {}; userInfo.username = docs[0].username; userInfo.userpwd = docs[0].userpwd; userInfo.userage = docs[0].userage; userInfo.usercity = doc[0].name; userInfo.userstate = result[0].name; userInfo.usercountry = result[0].country.name; respondData.data.push(userInfo); return res.json(respondData); }) }) });
使用postman模擬接口如下
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/19110.html
摘要:是在環(huán)境下對(duì)進(jìn)行便捷操作的對(duì)象模型工具因此,要使用,則必須安裝環(huán)境以及數(shù)據(jù)庫(kù)。使操作更簡(jiǎn)單便捷。找到記錄,并且將遞增,返回后的為之前的。這個(gè)屬性很有用,對(duì)數(shù)字直接進(jìn)行增減。,要返回的字段與的第二個(gè)參數(shù)一致。 Mongoose是在node.js環(huán)境下對(duì)mongodb進(jìn)行便捷操作的對(duì)象模型工具 因此,要使用mongoose,則必須安裝node.js環(huán)境以及mongodb數(shù)據(jù)庫(kù)。mongoo...
摘要:使用可以實(shí)現(xiàn)在一個(gè)中填充其他的。表示關(guān)聯(lián)注意被關(guān)聯(lián)的的必須是和才有效。類(lèi)型的時(shí),格式如為表示不填充,為時(shí)表示填充。以鍵值對(duì)的形式表示?;卣{(diào)函數(shù),接收兩個(gè)參數(shù),錯(cuò)誤和填充完的。參考數(shù)據(jù)庫(kù)的最簡(jiǎn)單實(shí)現(xiàn)使用之原文鏈接 Mongoose 是 MongoDB 的 ODM(Object Document Mapper)。 什么是ODM? 其實(shí)和ORM(Object Relational Mapp...
摘要:使用可以實(shí)現(xiàn)在一個(gè)中填充其他的。表示關(guān)聯(lián)注意被關(guān)聯(lián)的的必須是和才有效。封裝了很多查詢(xún)的方法,使得對(duì)數(shù)據(jù)庫(kù)的操作變得簡(jiǎn)單啦。這里分享一下方法用法。類(lèi)型的時(shí),格式如為表示不填充,為時(shí)表示填充。類(lèi)型,可選,指定附加的查詢(xún)條件。 Mongoose 是 MongoDB 的 ODM(Object Document Mapper)。 什么是ODM? 其實(shí)和ORM(Object Relational...
摘要:本項(xiàng)目持續(xù)更新中,開(kāi)源免費(fèi)與各位愛(ài)好技術(shù)達(dá)人共勉,注現(xiàn)階段仍在開(kāi)發(fā)中。。。。。 NodeJS+Express+MongoDb開(kāi)發(fā)的個(gè)人博客 NodeJS+Express搭建個(gè)人博客-環(huán)境搭建(一)NodeJS+Express搭建個(gè)人博客-gulp自動(dòng)化構(gòu)建工具使用(二)NodeJS+Express搭建個(gè)人博客-Express+Mongodb組合架構(gòu)介紹(三)NodeJS+Express...
摘要:在實(shí)際開(kāi)發(fā)過(guò)程中發(fā)現(xiàn),考試系統(tǒng)各個(gè)表集合都是需要關(guān)聯(lián),這種非關(guān)系型數(shù)據(jù)庫(kù),做起來(lái)反而麻煩了不少。數(shù)據(jù)中既有試卷的信息,也有很多題目。題目都屬于該試卷,改試卷又屬于當(dāng)前登錄系統(tǒng)的老師即創(chuàng)建試卷的老師。 這是我畢業(yè)項(xiàng)目,從0到1,前后臺(tái)獨(dú)立開(kāi)發(fā)完成。功能不多,在此記錄,溫故而知新!項(xiàng)目github地址:https://github.com/FinGet/Exam ,博客地址:https:/...
閱讀 2904·2021-11-17 09:33
閱讀 3686·2021-11-16 11:42
閱讀 3508·2021-10-26 09:50
閱讀 1363·2021-09-22 15:49
閱讀 3057·2021-08-10 09:44
閱讀 3697·2019-08-29 18:36
閱讀 3957·2019-08-29 16:43
閱讀 2236·2019-08-29 14:10