node.js - Mongoose 鉴别器不适用于嵌入式集合

标签 node.js mongodb mongoose

这是我的基本模式:

var mongoose = require("mongoose");
var utils= require("util");
var Schema = mongoose.Schema;

function BaseSchema(){
    Schema.apply(this, arguments);

    this.add({
        name: String,
        description: String,


    })

};

utils.inherits(BaseSchema, Schema);

module.exports = BaseSchema;

这是我的带有嵌入式 BaseSchema 的模型:

    var StepSchema = require('./step')
    var schema = mongoose.Schema({
        name: String,
        description: String,
        steps: [new StepSchema()]

    });

    schema.plugin(timestamps);

    var Funnel = mongoose.model('Funnel', schema);

    module.exports = Funnel;

现在每当我保存这样的记录时:

var funnel = new Funnel(req.body);
funnel.steps.push(new ActionStep({name: "test",actionType: "Notification"}));
funnel.save(function(err, b){
            if (err) {
                res.status(500).end();
            };

            res.json({funnel:b});

        });

鉴别器 key 未保存。

有什么想法吗?

最佳答案

我认为您应该在 Funnel 模型上使用鉴别器,然后在保存时将包含鉴别字段,就像在创建 Funner 模型之后,我们可以定义鉴别器:

var StepSchema = require('./step')
var schema = mongoose.Schema({
    name: String,
    description: String,
    steps: [new StepSchema()]

});

schema.plugin(timestamps);

var bossSchema = new BaseSchema({ name: String, actionType: String }); 

var Funnel = mongoose.model('Funnel', schema);

var Boss = Funnel.discriminator('Boss', bossSchema)

现在,在保存记录的同时:

var boss = new Boss({name: "test", actionType: "Notification" });
boss.save(function(err,boss) {

     if (err) {
            res.status(500).end();
        };

  });
var funnel = new Funnel(req.body);
funnel.steps.push(boss);
funnel.save(function(err, b){
        if (err) {
            res.status(500).end();
        };

        res.json({funnel:b});

    });

Which will produce output like this:

Boss:
{
"__v": 0,
"name": "test",
"actionType": "Notification",
"__t": "Boss",
"_id": "54a1951210a7a1b60316111a"
}

Funnel:
{
"steps":[
"__v": 0,
"name": "test",
"actionType": "Notification",
"__t": "Boss",
"_id": "54a1951210a7a1b60316111a"
]
}

如您所见,Boss 有不同的结构,特别是 _t 属性以及为不同对象定义的其他属性。但是实际上存储在相同的“步骤”集合中,并且可以这样查询。

因此,请检查您的集合中是否存在与您的架构定义不同的现有文档,并考虑所示的方法来表示不同“类型”对象的“多态”关联。

关于node.js - Mongoose 鉴别器不适用于嵌入式集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29592210/

相关文章:

javascript - VSCode ESLint 异步函数不支持

javascript - Node REPL 中的更改目录不起作用?

node.js - MongooseJS - 更新(不工作),findByIdAndUpdate(工作) - 为什么?

java - Spring Data MongoDB 始终将对象标识为新对象

javascript - 在 Puppeteer 中设置元素截图的宽度和高度

javascript - 限制 mongo 动态返回的字段

node.js - 如何在 sails 中而不是水线中使用 MongoDB

node.js - 预填充数据库-nodejs + mongodb

javascript - MongoDB 最佳实践 - 一对多关系

javascript - Sequelize : How to get record with createdat greater than 1 hour