当我尝试从get路由获取数据时,如果我只返回响应,则会获取数据。但是当我使用mongoose方法时,即mongoose.methods.summary = function(){...}。
这是代码(此代码转到catch块并始终返回错误):
router.get('/callsheets', authenticate, (req, res) => {
Callsheet.find(req.query)
.then(callsheets => res.send(callsheets.summary()))
.catch(err => res.json({ err }));
});
//the query is {creator: id}, which is passed from axios
//no errors in passing the query
以下是我的猫鼬模型的代码: 从'mongoose'进口猫鼬;
const callSheetSchema = new mongoose.Schema({
creator: { type: String, default: '' },
published: { type: Boolean, default: false },
sent: { type: Boolean, default: false },
completed: { type: Boolean, default: false },
archived: { type: Boolean, default: false },
client: { type: String, default: '' },
project: { type: String, default: '' },
production: { type: Array, default: [] },
wardrobe: { type: Array, default: [] }
});
callSheetSchema.methods.summary = function() {
const summary = {
id: this._id,
creator: this.creator,
published: this.published,
sent: this.sent,
completed: this.completed,
archived: this.archived,
client: this.client,
project: this.project,
production: this.production,
wardrobe: this.wardrobe
};
return summary;
};
export default mongoose.model('callsheet', callSheetSchema);
同样,如果我只返回res.send(callsheet)
,则会正确发送数据。如果我返回res.send(callsheet.summary())
,我会点击错误块。
非常感谢任何帮助。
答案 0 :(得分:0)
尝试使用虚拟财产http://mongoosejs.com/docs/guide.html#virtuals
callSheetSchema.virtual('summary').get(function () {
const summary = {
id: this._id,
creator: this.creator,
published: this.published,
sent: this.sent,
completed: this.completed,
archived: this.archived,
client: this.client,
project: this.project,
production: this.production,
wardrobe: this.wardrobe
};
return summary;
});
然后将其用作
router.get('/callsheets', authenticate, (req, res) => {
Callsheet.find(req.query)
.then(callsheets => res.send(callsheets.summary)) // <- not a method
.catch(err => res.json({ err }));
});
答案 1 :(得分:0)
尝试以这种方式导出
module.exports = callSheetSchema
代替export default callSheetSchema
答案 2 :(得分:0)
在节点上,我使用module.export而不是export default