简体   繁体   English

猫鼬动态mongodb集合名称

[英]Mongoose dynamic mongodb collection name

I am using mongoose driver for mongodb on node.js. 我在node.js上为mongodb使用mongoose驱动程序。 I have a schema as below. 我有一个如下的架构。

Using db.model I can get the model with the hardcoded collection name "aggregation". 使用db.model可以获得带有硬编码集合名称“ aggregation”的模型。 It works fine. 工作正常。

But how do I use the schema/model with a dynamic on-demand collection name? 但是,如何将模式/模型与动态按需集合名称一起使用? Basically, I will need to define a new collection on-demand and it will use the same schema. 基本上,我将需要按需定义一个新集合,它将使用相同的架构。

aggregationmodel.js aggregationmodel.js

var mongoose    = require('mongoose');

var db = mongoose.createConnection(configfile.mongodb.uriAggregation);

var aggregationSchema = mongoose.Schema({

    factorname   : { type: String, index: true },
    active       : { type: Boolean},

    total   : [{
            _id : { type: Number, index: true },
            ordervolume : Number,
            ordertips : Number,
            ordernationality : String,
            ordercancelled : Number
           }
          ]    
});

module.exports = db.model('aggregation', aggregationSchema, 'aggregation');

controller.js (this file references to model) controller.js(此文件引用模型)

var Aggregates     = require('../models/aggregationmodel.js');

All you basically need to do in instantiate a "new" model which has the required collection as an argument. 在实例化一个具有所需集合作为参数的“新”模型时,您基本上要做的所有事情。 It's just a matter of scoping really as to if the schema is available. 真正确定方案是否可用仅是范围的问题。 But you can always get the schema from an existing model and use in in the new instance: 但是,您始终可以从现有模型中获取模式并在新实例中使用:

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

mongoose.connect('mongodb://localhost/modtest');

var testSchema = new Schema({},{ strict: false });

var Test = mongoose.model( "Test", testSchema, "test" );


mongoose.connection.on("open", function(err,conn) {

  var ReModel = mongoose.model( "Redo", Test.schema, "redo" );

  var redo = new ReModel({ "a": 1 });

  redo.save(function(err,doc) {
    if (err) throw err;
    console.log( doc );
    console.log( "done" );
  });


});

The result there is that the actual document is inserted in the collection tied to the model you instantiated based on the schema extracted from the other model instance. 结果是,根据从其他模型实例提取的架构,将实际文档插入到与您实例化的模型绑定的集合中。

All you really need to do in your implementation is the same thing and supply the desired collection as an argument to feed into the standard instance creation method. 在实现过程中,您真正需要做的全部就是同一件事,并提供所需的集合作为参数,以馈入标准实例创建方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM