JAR*_*ans 4 mongoose mongodb nosql node.js
因此,我想创建一个基于客户端的分区模式,在其中将集合名称设置为function(),我的伪代码是这样的:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
var ConvForUserSchema = new Schema({
user_id: Number,
conv_hash: String,
archived: Boolean,
unread: Boolean
}, function CollectionName() {
return (this.user_id % 10000);
});
Run Code Online (Sandbox Code Playgroud)
是否有可能通过月球使读取和写入都能按预期工作?
使用函数动态获取模型。
/*
* Define Schemas as you used to
*/
const ConvForUserSchema = new Schema({
user_id: Number,
conv_hash: String,
archived: Boolean,
unread: Boolean
},{
versionKey : false,
strict: false
});
/*
* Define the dynamic function
*/
const models = {};
const getModel = (collectionName) => {
if( !(collectionName in models) ){
models[collectionName] = connection.model(
collectionName, ConvForUserSchema, collectionName
);
}
return models[collectionName];
};
Run Code Online (Sandbox Code Playgroud)
然后使用函数获取动态模型
const result = getModel("YourCollectionName").findOne({})
Run Code Online (Sandbox Code Playgroud)
集合名称逻辑在整个 Moongose 代码库中都是硬编码的,因此按照目前的情况,客户端分区是不可能的。
我的解决方案是直接使用 mongo 驱动程序 -
https://github.com/mongodb/node-mongodb-native
事实证明这很棒,与驱动程序一起工作的灵活性直接满足了所需的一切,并且 Moongose 开销在任何情况下似乎都没有增加太多。
您好,您只需要使用自己的名字声明架构模型,如下所示:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// our schema
function dinamycSchema(prefix){
var addressSchema = new Schema({
dir : {type : String, required : true}, //los 2 nombres delimitados por coma (,) ej. Alberto,Andres
city : {type : String, required: true}, //la misma estructura que para los nombres ej. Acosta, Arteta
postal : {type : Number, required : true},
_home_type : {type : Schema.Types.ObjectId, required : true, ref : prefix + '.home_type'},
state : {type : String, required : true},
telefono : String,
registered : {type : Date, default: Date.now }
});
return mongoose.model(prefix + '.address', addressSchema);
}
//no we export dinaymicSchema function
module.exports = dinamycModel;
Run Code Online (Sandbox Code Playgroud)
因此在您的代码中任何地方都可以执行此操作:
var userAdress = require('address.js')(id_user);
var usrAdrs1 = new userAddress({...});
userAdrs1.save();
Run Code Online (Sandbox Code Playgroud)
现在转到您的mongo shell和列表集合(使用mydb然后显示集合),您将看到一个带有uid前缀的地址的新集合。这样,猫鼬将为每个不同的用户uid创建一个新的集合地址。
干杯...
| 归档时间: |
|
| 查看次数: |
4723 次 |
| 最近记录: |