溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Mongoose中document與object有什么區(qū)別

發(fā)布時(shí)間:2021-02-03 16:03:15 來(lái)源:億速云 閱讀:155 作者:Leah 欄目:web開(kāi)發(fā)

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

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>

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

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

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

  • 2室1廳

  • 2室2廳

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

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

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

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

方法1:

利用toObject方法

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

方法2:

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

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ì)象,我們先來(lái)看看是不是這樣呢?

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]))

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

[object Array]
[object Object]

[object Array]
[object Object]

和我們預(yù)想中的一模一樣,那問(wèn)題不在這,那我們就探究探究docs[0]以及docs1[0]的原型把,看看它的原型到底是什么呢?知道JS的人,應(yīng)該都知道JS中的原型鏈。在此,我們就通過(guò)__proto__來(lái)粗暴地獲取對(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 } }

以及

{}

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

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

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

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

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI