Mongoose中document与object的区别示例详解

2020-06-17 05:43:06易采站长站整理

前言

本文主要给大家总结介绍了关于Mongoose中document与object区别的相关内容,分享出来供大家参考学习,其实这个问题其实是mongoose非常常见的问题,经常有很多以前没遇到这个问题的人都会被这个问题弄得怀疑人生。

我们先介绍一些问题的背景。

先看下面一段代码:


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>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
<!-- <%= docs %> -->
<ul>
<% docs.forEach(function(doc){ %>
<li><%= doc.type %></li>
<% }) %>
</ul>
</body>
</html>

在第一段代码中,通过

model.find
我们应该能够获取到根据queryCriteria获取的结果,结果应该是一个对象数组,类似于这样:


[{
"_id" : ObjectId("59bdeadb2a5c612514ee7970"),
"title" : "好楼层,中等装修,满5年,上门实拍",
"type" : "2室1厅",
"square" : "75.42平",
"direction" : "朝南",
"floor" : "中区/6层",
"unitPrice" : 47732,
"totalPrice" : 360,
"location" : null,
"specialExplain" : "满五",
"url" : "http://sh.lianjia.com//ershoufang/sh4528035.html",
"station" : "江杨北路",
"line" : "3号线",
"updateTime" : "2017-09-17 11:24:11"
}
{
"_id" : ObjectId("59bdeadb2a5c612514ee7971"),
"title" : "南北户型,厨卫全明,高区采光好,装修精美",
"type" : "2室2厅",
"square" : "90.92平",
"direction" : "朝南北",
"floor" : "高区/6层",
"unitPrice" : 46194,
"totalPrice" : 420,
"location" : null,
"specialExplain" : "满五",
"url" : "http://sh.lianjia.com//ershoufang/sh4546221.html",
"station" : "江杨北路",
"line" : "3号线",
"updateTime" : "2017-09-17 11:24:11"
}]

预期index.ejs应该渲染的页面是一个ul渲染的结果,类似于

2室1厅
2室2厅

当然,理想很丰满,现实很骨感。我就是死活渲染不出来doc.type。照理说应该是不可能的,在index.ejs中doc就是一个对象,我为什么不能获取doc的type属性呢?这不合理,太不合理了!