2016-06-02 5 views
0

Всякий раз, когда я пытаюсь передать любые данные в ответ в узле i я получаю вышеуказанную ошибку. Вот мой код для моего действия:Когда я пытаюсь передать данные в ответ в Node, я получаю: «error»: {«message»: «Can not read property« length »undefined»,

const show = (req, res, next) => { 
    User.findOne({"_id": req.currentUser._id}).then(function (user){ 
    console.log(user.events.id(req.params.id)); 
    return user.events.id(req.params.id); 
    return concert; 
    }) 
    .then(concert => concert ? res.json({ concert }) : next()) 
    .catch(err => next(err)); 
}; 

Консоль.log возвращает именно то, что я ожидаю. Если я изменю res.json на res.sendStatus ('200'), я получу 200 назад. Я думаю, что ошибка возникает из-за того, когда ответ пытается вычислить длину тела, которое он возвращает.

Трассировка стека Говорит:

Trace 
    at /Users/louisarnos/wdi/projects/capstone-project/capstone-backend/app/controllers/events.js:22:12 
    at process._tickCallback (node.js:369:9) 
TypeError: Cannot read property 'length' of undefined 
    at EmbeddedDocument.length (/Users/louisarnos/wdi/projects/capstone-project/capstone-backend/app/models/event.js:48:19) 
    at VirtualType.applyGetters (/Users/louisarnos/wdi/projects/capstone-project/capstone-backend/node_modules/mongoose/lib/virtualtype.js:77:25) 
    at EmbeddedDocument.Document.get (/Users/louisarnos/wdi/projects/capstone-project/capstone-backend/node_modules/mongoose/lib/document.js:870:18) 
    at applyGetters (/Users/louisarnos/wdi/projects/capstone-project/capstone-backend/node_modules/mongoose/lib/document.js:2173:35) 
    at EmbeddedDocument.Document.$toObject (/Users/louisarnos/wdi/projects/capstone-project/capstone-backend/node_modules/mongoose/lib/document.js:1957:5) 
    at EmbeddedDocument.Document.toJSON (/Users/louisarnos/wdi/projects/capstone-project/capstone-backend/node_modules/mongoose/lib/document.js:2199:15) 
    at Object.stringify (native) 
    at ServerResponse.json (/Users/louisarnos/wdi/projects/capstone-project/capstone-backend/node_modules/express/lib/response.js:242:19) 
    at ServerResponse.send (/Users/louisarnos/wdi/projects/capstone-project/capstone-backend/node_modules/express/lib/response.js:151:21) 
    at /Users/louisarnos/wdi/projects/capstone-project/capstone-backend/app/controllers/events.js:25:36 
    at process._tickCallback (node.js:369:9) 

Вот мой пользователь схема:

const userSchema = new mongoose.Schema({ 
    email: { 
    type: String, 
    unique: true, 
    required: true, 
    }, 
    token: { 
    type: String, 
    require: true, 
    }, 
    events: [EventSchema], 
    passwordDigest: String, 
}, { 
    timestamps: true, 
}); 

И моя События схема:

'use strict'; 

const mongoose = require('mongoose'); 

const eventSchema = new mongoose.Schema({ 
    artist: { 
    type: String, 
    required: true, 
    }, 
    location: { 
    venue: { 
     name: { 
     type: String, 
     required: true, 
     }, 
     city: { 
     type: String, 
     required: true, 
     }, 
     region: { 
     type: String, 
     required: true, 
     } 
    } 
    }, 
    date: { 
    month: { 
     type: String, 
     required: true, 
    }, 
    day: { 
     name: { 
     type: String, 
     required: true, 
     }, 
     num_of_day: { 
     type: Number, 
     required: true, 
     } 
    } 
    } 
}, { 
    timestamps: true, 
    toJSON: { virtuals: true }, 
}); 

eventSchema.virtual('length').get(function length() { 
    return this.text.length; 
}); 

const Event = mongoose.model('Event', eventSchema); 

module.exports = Event; 
+2

Я не думаю, что вы должны стягивать объект. и '{concert}' выглядит странно. ненужные скобки. –

+0

@KevinB, Да, вы правы. Я возился, пытаясь исправить ошибку. То же самое происходит без него. – Atache

+1

Вы просматривали трассировку стека, чтобы увидеть, где происходит ошибка? Посмотрел через источник? –

ответ

3

Это где брошено ошибка:

eventSchema.virtual('length').get(function length() { 
    return this.text.length; 
}); 

text не является свойством, определенным в вашей схеме, поэтому он не определен.

+0

Да, спасибо. Просто осознал это также. – Atache

0

У меня был виртуальный подарок внизу моей схемы, который я не использовал. Это было в качестве примера, как создать виртуальный атрибут.

 Смежные вопросы

  • Нет связанных вопросов^_^