node.js - 没有数组且没有引用的嵌入文档

标签 node.js mongodb mongoose

我有以下数据模型:

用户 - 地址 (一个用户有一个地址)。

出于可重用性的原因,我想在两个单独的文件中定义地址和用户的架构。这两个“实体”的关系应该作为嵌入文档来实现(没有数组,因为用户只有一个地址)。

阅读Embedded document without Array?https://github.com/LearnBoost/mongoose/pull/585使用 Mongoose 并不那么容易。根据 Stackoverflow-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
});

您可以嵌入“定义”,但不能嵌入已创建的架构。

关于node.js - 没有数组且没有引用的嵌入文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28008671/

相关文章:

node.js - Nodejs : iterate over req. 文件属性

javascript - 类型错误 : Cannot read property 'ip' of undefined - express-rate-limit

arrays - Linux 控制台中的 MongoDB 命令带有 --eval (print

node.js - Mongoose:对 $skip 和 $limit 之后的所有字段数求和

node.js - MongoDB 聚合函数,用于返回特定日期范围内的按日计数

mysql - createWriteStream 创建空文件,完成事件(在 stream.Writable 中)不触发

javascript - 获取具有多个子对象的 JavaScript 对象的特定值

mongodb - mongodump 给出段错误

javascript - 当您尝试引用架构时如何保存数据

node.js - 如何将 JSON 模式转换为 Mongoose 模式