javascript - 为什么文档的特定键的值变得“未定义”
问题描述
所以我有一个函数可以调用 Mongoose 查询,该查询会产生一组文档。我第二次循环这个数组以获取每个文档的信息并根据这些信息计算一些指标。
这是我得到的文档示例:
{ _id: 5decefed6575f603068d2213, asking: '3,000.00', currency: 'usd' }
{ _id: 5decefed6575f603068d2268, asking: '1,885.00', currency: 'usd' }
{ _id: 5decefed6575f603068d2247, asking: '2,950.00', currency: 'usd' }
{ _id: 5decefed6575f603068d2291, asking: '3,995.00', currency: 'usd' }
{
_id: 5decefed6575f603068d210a,
year: '2012',
asking: '8,000.00',
currency: 'eur'
}
{ _id: 5decefed6575f603068d2122 }
{ _id: 5decefed6575f603068d2218 }
{ _id: 5decefed6575f603068d221a }
{ _id: 5decefed6575f603068d2142, asking: '5,000.00', currency: 'eur' }
{ _id: 5decefed6575f603068d2209, year: '2014' }
正如您所看到的,有些有一个year
,asking
而currency
其他关键只有一个_id
。问题是,当我尝试从Object
它给我的时间中提取年份undefined
时,我完全没有问题提取asking
信息。
这是循环:
for (let j = 0; j < docs.length; j++) {
let currDoc = docs[j];
console.log(currDoc); // LINE MEANT FOR DEBUGGING. IT WORKS AND YIELDS THE INFORMATION I USED IN THE SAMPLE BUT WHEN CHANGING THIS TO "currDoc.year" I GET 'undefined".
if (currDoc.asking) {
countPrices++;
sumPrices += Number(currDoc.asking.replace(',', ''));
}
if (currDoc.year) {
console.log(currDoc.year);
distanceYears = Number(new Date().getFullYear()) - Number(currDoc.year);
countYears++;
sumYears += distanceYears;
console.log('\n' + currMake + ': ' + currModel + '\n\tYear:' + currDoc.year + '\n\tDistance: ' + distanceYears + '\n\tcountYears: ' + countYears);
// <--- PREVIOUS LINE MEANT FOR CONTROL AND DEBUGGING: NEVER APPEARS BECAUSE THE CONDITION ALWAYS FAIL -- undefined
}
}
为什么我不能得到年份信息,但我眨眼就得到了询问信息?
编辑:这是架构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var listingSchema = mongoose.Schema({
name: {type: String, require: true},
location: {type: String, require: true},
date: {type: Date, require: true},
asking: {type: String},
currency: {type: String},
condition: {type: String, require: true},
path: {type: String, require: true},
category: {type: String, require: true},
make: {type: String, require: true},
model: {type: String, require: true},
listingNumber: {type: String, require: true},
catFrom: {type: Schema.ObjectId, ref: 'Subcategory', require: true},
}, {strict: false});
module.exports = mongoose.model('Listing', listingSchema);
以及我的问题的解决方案: Mongoose/MongoDB 结果字段在 Javascript 中出现未定义
将文档转换为对象...
解决方案
推荐阅读
- teamcity - 使用 HTTP URI 中的构建参数触发 TeamCity 构建
- pandas - Pandas 条件分组
- python - TensorFlow 对象检测 API 的问题
- c# - 如何使用jQuery在隐藏字段中存储下拉选定的文本
- java - 在java中,我们可以在三元运算符中同时使用else和else if并在同一语句中构造3个条件吗?
- c++ - 有没有办法防止为不同类型创建另一个 if 语句?
- ubuntu - 无法检查电子版本
- typescript - 如何调试编译的打字稿源代码?
- django - 如何在不重新加载页面的情况下进行 Django 分页?
- next.js - Next.js 不传递路径参数