【问题标题】:Why won't my Mongoose model load?为什么我的 Mongoose 模型无法加载?
【发布时间】:2011-11-18 17:20:15
【问题描述】:

这是我的locationsModel.js 文件:

var LocationSchema, LocationsSchema, ObjectId, Schema, mongoose;
mongoose = require('mongoose');
Schema = mongoose.Schema;
ObjectId = Schema.ObjectId;
LocationSchema = {
  latitude: String,
  longitude: String,
  locationText: String
};
LocationsSchema = new Schema(LocationSchema);
LocationsSchema.method({
  getLocation: function(callback) {
    return console.log('hi');
  }
});
exports.Locations = mongoose.model('Locations', LocationsSchema, 'locations');

在我的控制器中,我有:

var Locations, mongoose;
mongoose = require('mongoose');
Locations = require('../models/locationsModel').Locations;
exports.search = function(req, res) {
  var itemText, locationText;
  Locations.getLocation('info', function(err, callback) {
    return console.log('calleback');
  });
  return;
};

当我运行它时,我收到以下错误:

TypeError: Object function model() {
    Model.apply(this, arguments);
  } has no method 'getLocation'

我错过了什么?

【问题讨论】:

  • 在你的控制器而不是Locations = require('../models/locationsModel').Locations;你可以简单地去Locations = mongoose.model('Locations')

标签: mongodb node.js mongoose


【解决方案1】:

我认为你追求的是静态而不是方法。

根据docs

我认为你应该如下定义getLocations 函数(看看你对getLocations 的使用,你有一个字符串参数以及回调:

LocationsSchema.statics.getLocation = function(param, callback) {
    return console.log('hi');
}

编辑:

staticsmethods 之间的区别在于您是在该类型的“类型”还是“对象”上调用它。改编自examples

BlogPostSchema.methods.findCreator = function (callback) {
  return this.db.model('Person').findById(this.creator, callback);
}

你会这样调用:

BlogPost.findById(myId, function (err, post) {
  if (!err) {
    post.findCreator(function(err, person) {
      // do something with the creator
    }
  }
});

【讨论】:

  • 非常感谢!哇,真棒!那么我什么时候使用staticmethod
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多