[英]Select all the fields in a mongoose schema
我想获得猫鼬模式的所有字段。 现在,我使用以下代码:
let Client = LisaClient.model('Client', ClientSchema)
let query = Client.findOne({ 'userclient': userclient })
query.select('clientname clientdocument client_id password userclient')
let result = yield query.exec()
但是我希望所有字段都是空的。 一如既往,提前谢谢
我不确定您是否希望以类似SQL的方式使用所有字段,还是以适当的MongoDB方式使用所有字段。
如果希望以正确的MongoDB方式使用它们,则只需删除query.select
行。 该行说只返回其中列出的字段。
如果您以类似SQL的方式表示,则MongoDB不会那样工作。 每个文档只有在插入时输入的字段。 如果在插入文档时只给了它某些字段,那么即使其他集合中的其他文档具有不同的字段,该文档也只会具有那些字段。
要确定集合中所有可用的字段,您必须找到所有文档,遍历所有文档,并使用找到的所有不同键构建对象。
如果您需要返回的每个文档始终具有您在选择中指定的字段,则只需在返回对象后对其进行转换。
const fields = ['clientname', 'clientdocument', 'client_id', 'password', 'userclient'];
let Client = LisaClient.model('Client', ClientSchema)
let query = Client.findOne({ 'userclient': userclient })
query.select(fields.join(' '))
let result = yield query.exec()
fields.forEach(field => result[field] = result[field]);
该forEach
循环会将您想要的所有字段设置为结果中的值(如果存在),或者将其设置为undefined
如果没有)。
MongoDB是无模式的,没有表,每个集合可以有不同类型的项目。通常,对象以某种方式相关或具有共同的基本类型。
使用以下方式检索个人记录
db.collectionName.findOne()
或db.collectionName.find().pretty()
要获取所有键名,您需要MapReduce
mapReduceKeys = db.runCommand({
"mapreduce": "collection_name",
"map": function() {
for (var key in this) {
emit(key, null);
}
},
"reduce": function(key, stuff) {
return null;
},
"out": "collection_name" + "_keys"
})
然后对结果集合进行非重复操作,以便找到所有键
db[mapReduceKeys.result].distinct("_id") //["foo", "bar", "baz", "_id", ...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.