Mongoose TypeError:实例化模式类型的对象时,对象不是函数

Mongoose TypeError: object is not a function when instantiating object of a schema type

本文关键字:对象 函数 TypeError 实例化 模式 类型 Mongoose      更新时间:2023-09-26

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

我有两个模式-"用户"answers"Tickit"。

User.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填充用户架构中的"Ticket"数组。

然而,在我的应用程序中,当我创建tickit时,应用程序崩溃,我得到了这个错误

var user = new User();
        ^
TypeError: object is not a function

尝试在函数中定义用户:

tickitSchema.pre('save', function(next){
   var User = require('../models/User');    
   // Code
});