<del id="d4fwx"><form id="d4fwx"></form></del>
      <del id="d4fwx"><form id="d4fwx"></form></del><del id="d4fwx"><form id="d4fwx"></form></del>

            <code id="d4fwx"><abbr id="d4fwx"></abbr></code>
          • Mongoose中document與object有什么區(qū)別

            這篇文章將為大家詳細(xì)講解有關(guān)Mongoose中document與object有什么區(qū)別,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

            網(wǎng)站的建設(shè)創(chuàng)新互聯(lián)專注網(wǎng)站定制,經(jīng)驗(yàn)豐富,不做模板,主營(yíng)網(wǎng)站定制開發(fā).小程序定制開發(fā),H5頁(yè)面制作!給你煥然一新的設(shè)計(jì)體驗(yàn)!已為履帶攪拌車等企業(yè)提供專業(yè)服務(wù)。

            router.get('/', function(req, res, next) {
             // res.render('index', { title: 'Express' });
             const model = mongoose.model('realestate');
             const queryCretia = {};
             model.find(queryCretia, (err, docs) => {
             res.render('index', {
             title: 'express',
             docs: docs
             })
             })
            });
            <!DOCTYPE html>
            <html>
             <head>
             <title><%= title %></title>
             <link rel='stylesheet' href='/stylesheets/style.css' />
             </head>
             <body>
             <h2><%= title %></h2>
             <p>Welcome to <%= title %></p>
             <!-- <%= docs %> -->
             <ul>
             <% docs.forEach(function(doc){ %>
             <li><%= doc.type %></li>
             <% }) %>
             </ul>
             </body>
            </html>

            在第一段代碼中,通過model.find我們應(yīng)該能夠獲取到根據(jù)queryCriteria獲取的結(jié)果,結(jié)果應(yīng)該是一個(gè)對(duì)象數(shù)組,類似于這樣:

            [{
             "_id" : ObjectId("59bdeadb2a5c612514ee7970"),
             "title" : "好樓層,中等裝修,滿5年,上門實(shí)拍",
             "type" : "2室1廳",
             "square" : "75.42平",
             "direction" : "朝南",
             "floor" : "中區(qū)/6層",
             "unitPrice" : 47732,
             "totalPrice" : 360,
             "location" : null,
             "specialExplain" : "滿五",
             "url" : "http://sh.lianjia.com//ershoufang/sh5528035.html",
             "station" : "江楊北路",
             "line" : "3號(hào)線",
             "updateTime" : "2017-09-17 11:24:11"
            }
            {
             "_id" : ObjectId("59bdeadb2a5c612514ee7971"),
             "title" : "南北戶型,廚衛(wèi)全明,高區(qū)采光好,裝修精美",
             "type" : "2室2廳",
             "square" : "90.92平",
             "direction" : "朝南北",
             "floor" : "高區(qū)/6層",
             "unitPrice" : 46194,
             "totalPrice" : 420,
             "location" : null,
             "specialExplain" : "滿五",
             "url" : "http://sh.lianjia.com//ershoufang/sh5546221.html",
             "station" : "江楊北路",
             "line" : "3號(hào)線",
             "updateTime" : "2017-09-17 11:24:11"
            }]

            預(yù)期index.ejs應(yīng)該渲染的頁(yè)面是一個(gè)ul渲染的結(jié)果,類似于

            • 2室1廳

            • 2室2廳

            當(dāng)然,理想很豐滿,現(xiàn)實(shí)很骨感。我就是死活渲染不出來doc.type。照理說應(yīng)該是不可能的,在index.ejs中doc就是一個(gè)對(duì)象,我為什么不能獲取doc的type屬性呢?這不合理,太不合理了!

            老實(shí)說,這個(gè)問題我之間也是遇到過,當(dāng)初我是想修改這個(gè)doc的屬性,但是死活沒有辦法修改,當(dāng)初也是花了很久找到原因。這次我就把這個(gè)問題好好地研究一下。

            先說結(jié)果,以及解決方法把。我比較喜歡劇透。愿意是因?yàn)樵俅畏祷氐膁oc是屬于Document的實(shí)例,而不是一個(gè)普通的對(duì)象。也就是說它和普通的對(duì)象是不一樣的,它沒有普通對(duì)象的一些方法,普通對(duì)象也沒有它身上的一些方法。

            解決方案有幾種,不過究其根本都是將這種document轉(zhuǎn)化為普通的對(duì)象:

            方法1:

            利用toObject方法

            docs.forEach(doc => {
             return doc.toObject();
            })

            方法2:

            利用JSON方法,這是我想到的一個(gè)方法,具體深層原因在這就不展開了:

            docs = JSON.stringify(docs);
            docs = JSON.parse(docs);

            方法3:

            利用lean方法:

            model.find().lean().exec((err, docs) => {
            ....
            })

            上述的三種方法應(yīng)該都能成功將find獲取的結(jié)果轉(zhuǎn)化為普通的對(duì)象。

            但是我還想知道到底document和一個(gè)普通的對(duì)象到底有什么區(qū)別,區(qū)別在哪里呢?

            我們假設(shè)find獲取的結(jié)果是docs,轉(zhuǎn)化為普通對(duì)象的結(jié)果是docs1?,F(xiàn)在我們就看一看這二者的區(qū)別。理論上docs和docs1都應(yīng)該是數(shù)組,而它們中元素都應(yīng)該是一個(gè)對(duì)象,我們先來看看是不是這樣呢?

            console.log(Object.prototype.toString.call(docs));
            consoele.log(Object.prototype.toString.call(docs[0]));
            
            console.log(Object.prototype.toString.call(docs1));
            console.log(Object.prototype.toString.call(docs1[0]))

            我們通過上述方法可以獲取docs以及docs1的類型以及其中元素的類型,結(jié)果是:

            [object Array]
            [object Object]
            
            [object Array]
            [object Object]

            和我們預(yù)想中的一模一樣,那問題不在這,那我們就探究探究docs[0]以及docs1[0]的原型把,看看它的原型到底是什么呢?知道JS的人,應(yīng)該都知道JS中的原型鏈。在此,我們就通過__proto__來粗暴地獲取對(duì)象的原型:

            console.dir(doc[0].__proto__);
            
            console.dir(docs[0].__proto__);

            結(jié)果是:

            model {
             db:
             NativeConnection {
              base:
              Mongoose {
              connections: [Array],
              models: [Object],
              modelSchemas: [Object],
              options: [Object],
              plugins: [Array] },
              collections: { realestates: [Object] },
              models: { realestate: [Object] },
              config: { autoIndex: true },
              replica: false,
              hosts: null,
              host: '127.0.0.1',
              port: 27017,
              user: undefined,
              pass: undefined,
              name: 'real_estate_info',
              options:
              { db: [Object],
              auth: {},
              server: [Object],
              replset: [Object],
              mongos: undefined },
              otherDbs: [],
              _readyState: 1,
              _closeCalled: false,
              _hasOpened: true,
              _listening: false,
              db:
              Db {
              domain: null,
              _events: [Object],
              _eventsCount: 6,
              _maxListeners: undefined,
              s: [Object],
              serverConfig: [Getter],
              bufferMaxEntries: [Getter],
              databaseName: [Getter],
              _listening: true },
              _events:
              { connected: [Function],
              error: [Function: bound bound consoleCall],
              disconnected: [Function: bound bound consoleCall],
              reconnected: [Function: bound bound consoleCall] },
              _eventsCount: 4 },
             discriminators: undefined,
             id: [Getter/Setter],
             __v: [Getter/Setter],
             _id: [Getter/Setter],
             schema:
             Schema {
              obj: undefined,
              paths: { _id: [Object], __v: [Object] },
              aliases: {},
              subpaths: {},
              virtuals: { id: [Object] },
              singleNestedPaths: {},
              nested: {},
              inherits: {},
              callQueue: [ [Array], [Array], [Array], [Array], [Array], [Array] ],
              _indexes: [],
              methods: {},
              statics: {},
              tree: { _id: [Object], __v: [Function: Number], id: [Object] },
              query: {},
              childSchemas: [],
              plugins: [ [Object], [Object], [Object], [Object] ],
              s: { hooks: [Object], kareemHooks: [Object] },
              options:
              { retainKeyOrder: false,
              typeKey: 'type',
              id: true,
              noVirtualId: false,
              _id: true,
              noId: false,
              validateBeforeSave: true,
              read: null,
              shardKey: null,
              autoIndex: null,
              minimize: true,
              discriminatorKey: '__t',
              versionKey: '__v',
              capped: false,
              bufferCommands: true,
              strict: true,
              pluralization: true },
              '$globalPluginsApplied': true,
              _requiredpaths: [] },
             collection:
             NativeCollection {
              collection: Collection { s: [Object] },
              opts: { bufferCommands: true, capped: false },
              name: 'realestates',
              collectionName: 'realestates',
              conn:
              NativeConnection {
              base: [Object],
              collections: [Object],
              models: [Object],
              config: [Object],
              replica: false,
              hosts: null,
              host: '127.0.0.1',
              port: 27017,
              user: undefined,
              pass: undefined,
              name: 'real_estate_info',
              options: [Object],
              otherDbs: [],
              _readyState: 1,
              _closeCalled: false,
              _hasOpened: true,
              _listening: false,
              db: [Object],
              _events: [Object],
              _eventsCount: 4 },
              queue: [],
              buffer: false,
              emitter:
              EventEmitter {
              domain: null,
              _events: {},
              _eventsCount: 0,
              _maxListeners: undefined } },
             '$__original_save': { [Function] numAsyncPres: 0 },
             save: { [Function: wrappedPointCut] '$originalFunction': '$__original_save', '$isWrapped': true },
             _pres:
             { '$__original_save': [ [Object], [Object], [Object] ],
              '$__original_remove': [ [Object] ] },
             _posts: { '$__original_save': [], '$__original_remove': [] },
             '$__original_remove': { [Function] numAsyncPres: 1 },
             remove:
             { [Function: wrappedPointCut]
              '$originalFunction': '$__original_remove',
              '$isWrapped': true },
             '$__original_validate': [Function],
             validate:
             { [Function: wrappedPointCut]
              '$originalFunction': '$__original_validate',
              '$isWrapped': true } }

            以及

            {}

            很顯然,問題就是在這里,docs[0]和docs[0]的原型并不是一個(gè)東西。而js中對(duì)象通過.或者是[]訪問屬性都是調(diào)用了Object中的某個(gè)方法,但具體什么方法我不太記得。然而docs中的原型或者其原型的原型也是沒有這個(gè)方法的,因此他就沒辦法去訪問這個(gè)屬性。

            其實(shí)docs[0].__proto__.__proto__是Model,docs[0].__proto__.__proto__.__proto__是Document,docs[0].__proto__.__proto__.__proto__.__proto__才是{}。

            至此,這個(gè)問題引起的一系列的探究也是告一段落了。其實(shí)Mongoose還有另外一些奇怪的地方,被人所詬病,在此也不一一細(xì)數(shù)了。從問題的發(fā)現(xiàn),到寫這篇文章大概花了大半天的時(shí)間,以前遇到問題就找到解決辦法就停止了,但是這一次通過這樣深入地去發(fā)現(xiàn),可能就會(huì)發(fā)掘到更多的東西。

            關(guān)于Mongoose中document與object有什么區(qū)別就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

            網(wǎng)頁(yè)標(biāo)題:Mongoose中document與object有什么區(qū)別
            標(biāo)題鏈接:http://www.jbt999.com/article38/ihsopp.html

            成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、面包屑導(dǎo)航外貿(mào)網(wǎng)站建設(shè)、App設(shè)計(jì)、App開發(fā)、靜態(tài)網(wǎng)站

            廣告

            聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:[email protected]。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

            網(wǎng)站托管運(yùn)營(yíng)

              <del id="d4fwx"><form id="d4fwx"></form></del>
              <del id="d4fwx"><form id="d4fwx"></form></del><del id="d4fwx"><form id="d4fwx"></form></del>

                    <code id="d4fwx"><abbr id="d4fwx"></abbr></code>
                  • 看操逼A片 | 久久久九一 | 欧美成人网站在线 | 中文字幕在线观看第一页2019 | 一级黄色视频国产 |