Mongoose:Coffeescript 中的递归嵌入文档

2024-03-28

基于这个例子 https://github.com/LearnBoost/mongoose/blob/master/examples/schema.js(有效):

var Comment = new Schema();

Comment.add({
    title : { type: String, index: true }
  , date : Date
  , body : String
  , comments : [Comment]
});

我想创建一个 CoffeeScript 版本

mongoose = require 'mongoose'
Schema = mongoose.Schema

Person = new Schema
Person.add
  mother: Person
  father: Person

但是它返回一个错误,我不明白为什么

TypeError: undefined is not a function
    at CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)
    at Function.interpretAsType (/path/node_modules/mongoose/lib/schema.js:202:10)
    at Schema.path (/path/node_modules/mongoose/lib/schema.js:162:29)
    at Schema.add (/path/node_modules/mongoose/lib/schema.js:110:12)
    at Object.<anonymous> (/path/Models/test.coffee:6:10)
    at Object.<anonymous> (/path/Models/test.coffee:10:4)
    at Module._compile (module.js:411:26)
    at Object.run (/usr/local/lib/node_modules/coffee-script/lib/coffee-script.js:57:25)
    at /usr/local/lib/node_modules/coffee-script/lib/command.js:147:29
    at /usr/local/lib/node_modules/coffee-script/lib/command.js:115:26

编辑:好的,我发现当 Person 不是数组(在括号中)时它不起作用,但为什么呢?


嵌入文档只能作为数组中的项目存在。这是设计使然,你可以问作者 https://github.com/learnboost因为他们的原因:)

您可能想使用DBRef:

Person = new Schema
  mother: { type: Schema.ObjectId, ref: 'Person' }
  father: { type: Schema.ObjectId, ref: 'Person' }

(请注意,您不需要add call)

See the 填充/DBRef 的文档 http://mongoosejs.com/docs/populate.html.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mongoose:Coffeescript 中的递归嵌入文档 的相关文章

随机推荐