首页 > 解决方案 > 为什么文档的特定键的值变得“未定义”

问题描述

所以我有一个函数可以调用 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' }

正如您所看到的,有些有一个yearaskingcurrency其他关键只有一个_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 中出现未定义

将文档转换为对象...

标签: javascriptnode.jsjsonmongoose

解决方案


推荐阅读