gpt4 book ai didi

javascript - Mongoose:Coffeescript 中的递归嵌入式文档

转载 作者:可可西里 更新时间:2023-11-01 09:11:50 28 4
gpt4 key购买 nike

基于 this example (有效):

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 不是数组(在括号中)时它不起作用,但为什么呢?

最佳答案

嵌入文档只能作为数组中的项目存在。那是设计使然,你可以问the authors因为他们的原因:)

您可能想使用 DBRef:

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

(注意您不需要 add 调用)

参见 docs for populate/DBRef .

关于javascript - Mongoose:Coffeescript 中的递归嵌入式文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7992185/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com