开发者

Problems exporting model functions with Mongoose

开发者 https://www.devze.com 2023-03-24 16:06 出处:网络
I\'m struggling with creating model functions for Mongoose models. I define a method here: Schema.listingSchema.method(\'applyPrice\', function() {

I'm struggling with creating model functions for Mongoose models. 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 relev开发者_开发问答ant 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();
0

精彩评论

暂无评论...
验证码 换一张
取 消