子文档基于另一个文档

时间:2015-04-21 06:59:34

标签: mongodb mongoose

我想知道Mongoose是否可以根据另一个文档创建一个子文档。

通常我会做这样的事情:

'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var CountrySchema = new Schema({
    name: String,
    info: String,
    cities : [
        {
            type: Schema.ObjectId, 
            ref: 'Ressource'
        }
    ]
});

module.exports = mongoose.model('Country', CountrySchema);

然而,这会创建一个新文档,然后通过id将其引用到country文档。这不是我想要的,我希望resource文档嵌套在country文档中。我该怎么做?

1 个答案:

答案 0 :(得分:0)

我发现这解决了我的问题:

'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ressourceSchema = require('../ressource/ressource.model');

var CountrySchema = new Schema({
    name: String,
    info: String,
    cities : [
        ressourceSchema.schema
    ]
});

module.exports = mongoose.model('Country', CountrySchema);