【问题标题】:Mongoose TypeError: object is not a function when instantiating object of a schema typeMongoose TypeError:实例化模式类型的对象时对象不是函数
【发布时间】:2015-06-11 20:31:12
【问题描述】:

我遇到的问题是 mongoose 不允许我在不同模式的“pre”方法中实例化模式类型的对象。

我有 2 个架构 - 'User' 和 'Tickit'。

用户.js

var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');
var Schema   = mongoose.Schema;
var Tickit   = require('../models/Tickit');

var userSchema = new Schema({
    email        : String,
    password     : String,
    tickits      : [Tickit.tickitSchema]

});

userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.password);
};

module.exports = mongoose.model('User', userSchema);

和 Ticket.js

var mongoose    = require('mongoose');
var User        = require('../models/User');
var Schema      = mongoose.Schema;
var tickitSchema = new Schema({
    title: String,
    description: String,
    author : { type: Schema.Types.ObjectId, ref: 'User' },
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}]
});

tickitSchema.pre('save', function(next){

    var user = new User();
    user.tickits.push ({id:this._id});
    user.save(function(err){
        if(err)
            res.send(err)

            .populate('tickits')

            .exec(function(err, blah){
                if(err) res.send(err);
            })
        res.json(blah); 
    })
    next();
})
module.exports = mongoose.model('Tickit', tickitSchema);

我试图用 Ticket 中的 pre 方法做的是在每次创建 Ticket 时使用该 Ticket 的 id 填充用户模式中的“Tickits”数组。

但是,当我在我的应用程序中创建一个 tickit 时,应用程序崩溃并且我收到此错误

var user = new User();
        ^

TypeError: object is not a function

【问题讨论】:

  • 你找到答案了吗?

标签: javascript node.js mongodb mongoose


【解决方案1】:

尝试在你的函数中定义用户:

tickitSchema.pre('save', function(next){

   var User = require('../models/User');    

   // Code

});

【讨论】:

  • 这成功了!谢谢你。在我发布这个问题后不久,我意识到创建一个新用户不是我需要做的。相反,我应该使用刚刚创建的 tickit 的 id 填充 现有 (当前登录的)用户的 tickits 数组
猜你喜欢
  • 2015-10-28
  • 2015-09-20
  • 2015-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多