Mongodbtypes的参考节点

我想在节点中的模型中引用另一个对象,

User = new Schema({ username: { type: String, index: {unique: true} } }); Idea = new Schema({ Creator: { type: User } }); 

但我得到这个错误Undefined type at "creator" Did you try nesting Schemas? You can only nest using refs or arrays. Undefined type at "creator" Did you try nesting Schemas? You can only nest using refs or arrays. 我相信我想使用裁判,但无法find文件,有人可以帮我。 谢谢

我在这里发现了自己的问题的答案。

 User = new Schema({ username: { type: String, index: {unique: true} } }); Idea = new Schema({ Creator: { type: Schema.ObjectId, ref: 'User' } }); 

我想回答这个问题,因为这是Google的第一个结果。

不,您不能使用嵌套架构作为其他答复说。 但是你仍然可以在不同的模式中使用同一个对象。

 // Regular JS Object (Not a schema) var Address = { address1: String, address2: String, city: String, postalcode: String }; var Customer = new Schema({ firstname: String, lastname: String, address: Address }); var Store = new Schema({ name: String, address: Address }); 

通过这种方式,您可以修改地址对象,以便在共享该对象的所有模式上进行更改。

这里是手动@ refs的链接 。

你不能在模式devise级别使用refs。

我决定通过使我的子文档嵌套types解决我的项目类似的问题

  Foo = new Schema({ name: String, bar: { name: String } }); 

如果你需要Bar成为自己的模型,显然这是行不通的。 也许是因为你把它作为其他对象的模型。 在我的情况下,这是我所需要做的,但是Mongoose指南的子文档部分没有提到它作为一个选项,所以我将这个讨论添加进来。