2013-03-02 44 views
1

当我试图在我的应用程序的代码:的NodeJS - 猫鼬(对象没有方法 “ID”)

应用程序/模型/ Post.coffee

mongoose  = require "mongoose" 
CommentModel = require "./Comment" 
Comment  = CommentModel.Schema 
Schema  = mongoose.Schema 

Post = new Schema { 
    title: String, 
    slug: {type: String, index: { unique: true, dropDubs: true }}, 
    content: String, 
    author: String, 
    tags: [String], 
    comments: [Comment], 
    created: { type: Date, default: Date.now } 
} 

Post.statics.findBySlug = (slug, cb) -> 
    this.model("Post").findOne({ slug: slug }, cb) 

PostModel = mongoose.model "Post", Post 

module.exports = PostModel 

应用程序/模型/评论.coffee

mongoose = require("mongoose") 
Schema = mongoose.Schema 

Comment = new Schema { 
    author: String, 
    content: String, 
    approved: Boolean, 
    created: { type: Date, default: Date.now } 
} 


CommentModel = mongoose.model "Comment", Comment 

module.exports = CommentModel 

应用程序/控制器/ PostsController.coffee(只是一个法)

commentDestroy: (req, res, next) -> 
    Post.findBySlug req.params.slug, (err, doc) -> 
     if (err) 
      return next err 

     if doc == null 
      res.send 404 
      return 

     doc.comments.id(req.params.comment).remove() 
     doc.save (err) -> 
      if err 
       next err 

      res.json doc 

它以错误结束:

TypeError: Object [object Object],[object Object],[object Object],[object Object],[object Object] has no method 'id' 
    at Promise.PostsController.commentDestroy (/home/r41ngoloss/Projects/www/my-express/app/controllers/PostsController.js:88:22) 
    at Promise.addBack (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/promise.js:128:8) 
    at Promise.EventEmitter.emit (events.js:96:17) 
    at Promise.emit (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/promise.js:66:38) 
    at Promise.complete (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/promise.js:77:20) 
    at Query.findOne (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/query.js:1533:15) 
    at model.Document.init (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/document.js:229:11) 
    at model.init (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/model.js:192:36) 
    at Query.findOne (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/query.js:1531:12) 
    at exports.tick (/home/r41ngoloss/Projects/www/my-express/node_modules/mongoose/lib/utils.js:408:16) 

我已经试图找到解决我的问题,但我发现只是this,我想,我必须按正确的顺序模式(通过要求)。

感谢您的每一个答案。

回答

1

您得到该错误的原因是您没有在Post.coffee文件中正确获取Comment模式。当我做你做的时候,Comment变量是undefined。修改您的Post.coffee文件的顶端:

mongoose = require "mongoose" 
Comment = mongoose.model('Comment').schema 
Schema = mongoose.Schema 

现在Comment变量是Comment模型的架构。

+1

谢谢!这是错误的! – user1607808 2013-03-04 18:30:17