mongodb 从猫鼬模型获取模式属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17035297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting schema attributes from Mongoose Model
提问by user1460015
I'm using Mongoose.js to create models with schemas.
我正在使用 Mongoose.js 创建带有模式的模型。
I have a list of models (many) and at times I'd like to get the attributes/keys that make up a particular model.
我有一个模型列表(很多),有时我想获取构成特定模型的属性/键。
Is there a method to pull out the attribute schemas for any given model?
有没有一种方法可以提取任何给定模型的属性模式?
For example,
例如,
var mySchema = module.exports = new Schema({
SID: {
type: Schema.Types.ObjectId
//, required: true
},
teams: {
type: [String]
},
hats: [{
val: String,
dt: Date
}],
shields: [{
val: String,
dt: Date
}],
shoes: [{
val: String,
dt: Date
}]
}
);
);
Is it possible to pull out/identify the attributes of the schema [SID, hats, teams, shields, shoes]
??
是否可以提取/识别模式的属性[SID, hats, teams, shields, shoes]
?
回答by gustavohenke
Yes, it is possible.
对的,这是可能的。
Each schema has a paths
property, that looks somewhat like this (this is an example of my code):
每个模式都有一个paths
属性,看起来有点像这样(这是我的代码示例):
paths: {
number: [Object],
'name.first': [Object],
'name.last': [Object],
ssn: [Object],
birthday: [Object],
'job.company': [Object],
'job.position': [Object],
'address.city': [Object],
'address.state': [Object],
'address.country': [Object],
'address.street': [Object],
'address.number': [Object],
'address.zip': [Object],
email: [Object],
phones: [Object],
tags: [Object],
createdBy: [Object],
createdAt: [Object],
updatedBy: [Object],
updatedAt: [Object],
meta: [Object],
_id: [Object],
__v: [Object]
}
You can access this through an model too. It's under Model.schema.paths
.
您也可以通过模型访问它。它在Model.schema.paths
.
回答by js_gandalf
Don't have enough rep to comment, but this also spits out a list and loops through all of the schema types.
没有足够的代表来评论,但这也会输出一个列表并遍历所有模式类型。
mySchema.schema.eachPath(function(path) {
console.log(path);
});
should print out:
应该打印出来:
number
name.first
name.last
ssn
birthday
job.company
job.position
address.city
address.state
address.country
address.street
address.number
address.zip
email
phones
tags
createdBy
createdAt
updatedBy
updatedAt
meta
_id
__v
Or you could get all Attributes as an Array like this:
或者您可以像这样将所有属性作为数组获取:
var props = Object.keys(mySchema.schema.paths);
回答by styopdev
Solution for lodash, function which picked all schema properties, excluding specified
lodash 的解决方案,选择所有模式属性的函数,不包括指定的
_.mixin({ pickSchema: function (model, excluded) {
var fields = [];
model.schema.eachPath(function (path) {
_.isArray(excluded) ? excluded.indexOf(path) < 0 ? fields.push(path) : false : path === excluded ? false : fields.push(path);
});
return fields;
}
});
_.pickSchema(User, '_id'); // will return all fields except _id
_.pick(req.body, _.pickSchema(User, ['_id', 'createdAt', 'hidden'])) // all except specified properties
read more here https://gist.github.com/styopdev/95f3fed98ce3ebaedf5c
在这里阅读更多https://gist.github.com/styopdev/95f3fed98ce3ebaedf5c
回答by lucas teles
My solution uses mongoose model.
我的解决方案使用猫鼬模型。
Schema attributes
架构属性
const schema = {
email: {
type: String,
required: 'email is required',
},
password: {
type: String,
required: 'password is required',
},
};
Schema
架构
const FooSchema = new Schema(schema);
Model
模型
const FooModel = model('Foo', FooSchema);
Get attributes from model:
从模型中获取属性:
Object.keys(FooModel.schema.tree)
Result:
结果:
[
'email',
'password',
'_id',
'__v'
]
回答by e-nouri
If you want to have only the attributes you added and not the add methods by the ORM that starts with '$___', you have to turn the document into object then access the attributes like this:
如果您只想拥有您添加的属性,而不是 ORM 以“$___”开头的添加方法,则必须将文档转换为对象,然后像这样访问属性:
Object.keys(document.toObject());
回答by Footniko
In case you want to have all property values (including nested and populated properties), just use toObject()
method:
如果您想拥有所有属性值(包括嵌套和填充的属性),只需使用toObject()
方法:
let modelAttributes = null;
SomeModel.findById('someId').populate('child.name').exec().then((result) => {
modelAttributes = result.toObject();
console.log(modelAttributes);
});
The output would be:
输出将是:
{
id: 'someId',
name: 'someName',
child: {
name: 'someChildName'
}
...
}
回答by Dilshan Liyanage
Just insert the field name you like to get.
只需插入您想要获取的字段名称。
let fieldName = 'birthday'
console.log(mySchema.schema.paths[fieldName].instance);
回答by crownlessking
The accepted answer did not work for me. But using Mongoose 5.4.2 I was able to get the keys by doing the following:
接受的答案对我不起作用。但是使用 Mongoose 5.4.2 我能够通过执行以下操作来获取密钥:
const mySchema = new Schema({ ... });
const arrayOfKeys = Object.keys(mySchema.obj);
I'm using typescript, however. That might have been the problem.
但是,我正在使用typescript。那可能是问题所在。