每当我尝试将任何数据传递给Node中的响应时,我都会收到上述错误。这是我的show动作的代码:
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));
};
console.log完全返回我期望的内容。如果我将res.json更改为res.sendStatus(' 200')我将返回200。我认为错误源于响应试图计算它返回的身体长度时。
Stack Trace说:
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;
答案 0 :(得分:3)
这是抛出错误的地方:
eventSchema.virtual('length').get(function length() {
return this.text.length;
});
text
不是架构中定义的属性,因此未定义。
答案 1 :(得分:0)
我的架构底部有一个虚拟礼物,我没有使用。它就是如何构建虚拟属性的示例。