成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專(zhuān)欄INFORMATION COLUMN

mongoose的關(guān)聯(lián)操作

張紅新 / 2080人閱讀

摘要:實(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)小眉目了。

node v8.5.0

mongodb

結(jié)合一個(gè)接口理解

結(jié)合promise-async-await

一般采用mvc模式,本文就直接在express里直接寫(xiě)了

1. 首先建立了一個(gè)mongoose-ref項(xiàng)目

直接使用了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)不同的表中。

5.使用populate關(guān)聯(lián)查詢(xú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模擬接口如下

當(dāng)然這個(gè)關(guān)聯(lián)查詢(xún)也可以使用promise-async-await不過(guò)有時(shí)候看著這回調(diào),層層包含還挺好看,或者這也是js的一大美感呢

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/19110.html

相關(guān)文章

  • Mongoose簡(jiǎn)要API

    摘要:是在環(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...

    王巖威 評(píng)論0 收藏0
  • Mongoose 之 Population 使用

    摘要:使用可以實(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...

    timger 評(píng)論0 收藏0
  • [轉(zhuǎn)]mongodb中populate方法

    摘要:使用可以實(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...

    ranwu 評(píng)論0 收藏0
  • NodeJS+Express搭建個(gè)人博客-環(huán)境搭建(一)

    摘要:本項(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...

    Clect 評(píng)論0 收藏0
  • 在線考試系統(tǒng)(vue2 + elementui + express4 + MongoDB)

    摘要:在實(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:/...

    warmcheng 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

閱讀需要支付1元查看
<