简体   繁体   English

用Mongoose导出模型函数时出现问题

[英]Problems exporting model functions with Mongoose

I'm struggling with creating model functions for Mongoose models. 我正在努力为Mongoose模型创建模型函数。 I define a method here: 我在这里定义一个方法:

Schema.listingSchema.method('applyPrice', function() {
  this.price = priceFromString(this.title);
});

and I access it here: 我在这里访问它:

var listing = new Listing();

// assign all relevant data
listing.title = title;
...

// pull the price out of the title and description
listing.applyPrice(listing);

where 哪里

Listing = mongoose.model('Listing', Schema.listingSchema);

and I receive the error: 我收到错误:

TypeError: Object #<model> has no method 'applyPrice'

Can anyone see the issue? 谁能看到这个问题?

How are you defining your schema? 您如何定义架构? Usually you would do something like this: 通常,您会执行以下操作:

var listingSchema = new mongoose.Schema({
  title: String
});
listingSchema.method('applyPrice', function() {
  this.price = priceFromString(this.title);
});

mongoose.model('Listing', listingSchema);
var Listing = mongoose.model('Listing');

var listing = new Listing({ title: 'Title' });
listing.applyPrice();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM