Mongoose: recursive inline document in Coffeescript

Based on this example (which works):

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

I wanted to create a version of CoffeeScript

 mongoose = require 'mongoose' Schema = mongoose.Schema Person = new Schema Person.add mother: Person father: Person 

However, it returns an error, and I do not understand why

 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 

EDIT: Well, I found out that this does not work when Person is not an array (in brackets), but why?

+4
source share
1 answer

Inline documents can only exist as elements in an array. This is by design, you can ask the authors for their reasons :)

You might want to use DBRef :

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

(note that you do not need add call)

See docs for populating / DBRef .

+6
source

Source: https://habr.com/ru/post/1379440/


All Articles