当从Mongoose 3.x升级到Mongoose 4.x时,我如何在模式内使用模式?

4

I have 2 files:

keyFeature:

mongoose = require('mongoose');

Schema = mongoose.Schema;

DescriptionSchema = require('./description');

KeyFeatureSchema = new Schema({
  descriptions: [DescriptionSchema],
  title: String,
  key: String,
  display: String,
  feature: {
    type: Schema.Types.ObjectId,
    ref: 'Module'
  }
});

module.exports = KeyFeatureSchema;

描述:

mongoose = require('mongoose');

DescriptionSchema = new mongoose.Schema();

DescriptionSchema.add({
  display: String,
  subdescriptions: [String]
});

module.exports = DescriptionSchema;

我该如何重写以兼容Mongoose 4的.add语法?
1个回答

1

我不确定我是否理解了你的问题,但是这是我得到的。

根据mongoose .add documentation for 4.5.2,添加语法仍然相同。因此,我使用你的模式创建了一个简单的testing.js文件。我创建了一个keyFeature对象,并在其中一个描述数组中保存了一个对象。之后,我使用mongo控制台连接到mongod并查询keyfeatures集合。该对象已成功插入到数据库中。

以下是我的代码:

var mongoose = require('mongoose');
var DescriptionSchema = require('./description.js');
var KeyFeatureSchema = require('./keyFeature.js');

mongoose.connect('mongodb://localhost/mongoose-testing', function(err)    {
    if(err){
        console.log('Could not connect to mongoose', err);
    }else{
        console.log('Successfully connected to mongoose');
        mongoose.model('Description', DescriptionSchema);
        mongoose.model('Keyfeature', KeyFeatureSchema);
        var Keyfeature = mongoose.model('Keyfeature');

        new Keyfeature({
            descriptions: [{
                display: 'This is the display content from descriptions',
                subdescriptions: ['Subdescription 1']
            }],
            title: 'tittle',
            key: 'key',
            display: 'display'
        }).save(function(err){
            if(err){
                console.log('Error when saving', err);
            }else{
                console.log('Saved');
            }
        });
    }
});

测试使用的是mongoose@4.5.2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接