没有数组且没有参考的嵌入式文档
Embedded document without array and without reference
我有以下数据模型:
用户 - 地址
(一个用户有一个地址)。
出于可重用性的原因,我想在两个单独的文件中定义地址和用户的架构。这两个 "entities" 的关系应该作为嵌入式文档实现(没有数组,因为用户只有一个地址)。
阅读 Embedded document without Array? and https://github.com/LearnBoost/mongoose/pull/585 使用 Mongoose 并不容易。根据 Whosebug-thread,它可以像这样完成:
addressPersistenceModel.js:
var address = {
street: String,
zipCode: String,
...
};
module.exports = address;
userPersistenceModel.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var addressDefinition = require('./addressPersistenceModel');
var Address = new Schema(addressDefinition);
var UserEntityModel = new Schema({
firstname: String,
lastname: String,
...
address: Address
});
mongoose.model('User', UserEntityModel);
但是我仍然得到错误
TypeError: Undefined type at `address`
Did you try nesting Schemas? You can only nest using refs or arrays.
像那样定义你的实体
var UserEntityModel = new Schema({
firstname: String,
lastname: String,
address: addressDefinition
});
您可以嵌入 "definition" 但不能嵌入已创建的架构。
我有以下数据模型:
用户 - 地址 (一个用户有一个地址)。
出于可重用性的原因,我想在两个单独的文件中定义地址和用户的架构。这两个 "entities" 的关系应该作为嵌入式文档实现(没有数组,因为用户只有一个地址)。
阅读 Embedded document without Array? and https://github.com/LearnBoost/mongoose/pull/585 使用 Mongoose 并不容易。根据 Whosebug-thread,它可以像这样完成:
addressPersistenceModel.js:
var address = {
street: String,
zipCode: String,
...
};
module.exports = address;
userPersistenceModel.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var addressDefinition = require('./addressPersistenceModel');
var Address = new Schema(addressDefinition);
var UserEntityModel = new Schema({
firstname: String,
lastname: String,
...
address: Address
});
mongoose.model('User', UserEntityModel);
但是我仍然得到错误
TypeError: Undefined type at `address`
Did you try nesting Schemas? You can only nest using refs or arrays.
像那样定义你的实体
var UserEntityModel = new Schema({
firstname: String,
lastname: String,
address: addressDefinition
});
您可以嵌入 "definition" 但不能嵌入已创建的架构。