创建嵌入式文档mongoose

时间:2017-02-05 18:07:52

标签: node.js mongodb mongoose mongoose-schema

我有以下mongoose架构:

'use strict';

const PostSchema = new Schema({
    description: require('../fields/description'),
    image: require('../fields/image'),
    createdAt: require('../fields/createdAt'),
    location: Location,
    owner: require('../fields/owner') }, {
    toObject: {
        virtuals: true,
        getters: true,
        setters: true
    },
    toJSON: {
        virtuals: true,
        getters: true,
        setters: true
    } });

module.exports = mongoose.model('Post', PostSchema);

LocationSchema.js

'use strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const LocationSchema = new Schema({
    description: {
    type: String,
    required: true
},
    point:{
    type: [Number],
    index: '2d',
    required: true
},
    createdAt:{
    type: Date,
    required: true,
    default: new Date()
}
});

module.exports = mongoose.model('Location', LocationSchema);

当我重新启动我的nodejs服务器时,我发出以下错误消息:

  

TypeError:Model处的未定义类型location您是否尝试过嵌套   架构?您只能使用refs或数组进行嵌套。

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

此处的错误表示您未在帖子集合中提及位置键,如果您想为您的帖子集合提供位置ID,则必须提供对您的集合的引用。

示例:

var PostSchema = new mongoose.Schema({
  location: [{ type: mongoose.Schema.Types.ObjectId, ref: 'location' }]
});