当试图将项目添加到mongoose数组时,“对象{}没有方法”投射“错误”

我试图创build一个todo应用程序使用node.js,mongoose和主干学习的目的。 直到现在我定义了这些模型:

var TaskSchema = new mongoose.Schema({ title: { type:String }, content: { type:String } , created: {type:Date, 'default':Date.now}, due: {type:Date}, accountId: {type:mongoose.Schema.ObjectId} }); var Task = mongoose.model('Task',TaskSchema); var AccountSchema = new mongoose.Schema({ email: { type:String, unique: true}, password: { type:String } , name: { first: {type:String}, last: { type:String } }, birthday: { day: {type:Number, min:1, max:31, required:false}, month: {type:Number, min:1, max:12, required:false}, year: {type:Number} }, photoUrl: {type:String}, biography:{type:String}, tasks:[Task] }); var Account = mongoose.model('Account',AccountSchema); 

另外,我还有以下添加任务的方法:

 var enter_new_task = function(options,callback){ var title = options.title; var content = options.content; var due = options.due; var account = options.account; var task = new Task({ title: title, content: content, due: due, accountId: account._id }); account.tasks.push(task); account.save(function(err) { if ( err ) { console.log("Error while saving task: " + err); }else{ callback(); } }) } 

但是当我真的添加一个任务,我得到一个错误,说:

“对象{}没有方法”投射“”

使用以下堆栈跟踪:

  at Array.MongooseArray._cast (/home/lior/workspace/todo_express/node_modules/mongoose/lib/types/array.js:107:30) at Object.map (native) at Array.MongooseArray.push (/home/lior/workspace/todo_express/node_modules/mongoose/lib/types/array.js:261:23) at Object.enter_new_task (/home/lior/workspace/todo_express/models/Account.js:107:17) at /home/lior/workspace/todo_express/app.js:104:18 at Promise.<anonymous> (/home/lior/workspace/todo_express/models/Account.js:41:4) at Promise.<anonymous> (/home/lior/workspace/todo_express/node_modules/mongoose/node_modules/mpromise/lib/promise.js:162:8) at Promise.EventEmitter.emit (events.js:95:17) at Promise.emit (/home/lior/workspace/todo_express/node_modules/mongoose/node_modules/mpromise/lib/promise.js:79:38) at Promise.fulfill (/home/lior/workspace/todo_express/node_modules/mongoose/node_modules/mpromise/lib/promise.js:92:20) 9 

看来问题是用新的任务数组的任务线。

无法find任何东西在谷歌或堆栈,所以我想知道,有没有人有什么错误的想法?

谢谢!

该错误在AccountSchema定义中。 子文档types应该是模式,而不是模型。

 var AccountSchema = new mongoose.Schema({ //... tasks:[TaskSchema] }); 

或者,如果您没有直接访问模式,只能访问模型,则可以使用点符号访问模型的模式,如下所示:

 var AccountSchema = new mongoose.Schema({ //... tasks:[Task.schema] }); 

如果你已经在另一个文件中定义了你的模式,并且正在使用类似这样的东西,

 module.exports = mongoose.model('Task', TaskSchema);