当前位置 : 主页 > 网页制作 > Nodejs >

node.js – 从Mongoose 3.x升级到Mongoose 4.x时,如何在模式中使用模式?

来源:互联网 收集:自由互联 发布时间:2021-06-16
我有2个文件: 关键特点: mongoose = require('mongoose');Schema = mongoose.Schema;DescriptionSchema = require('./description');KeyFeatureSchema = new Schema({ descriptions: [DescriptionSchema], title: String, key: String, display:
我有2个文件:

关键特点:

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语法兼容?

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

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

这是我的代码

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测试

网友评论