我在运行查询后从MongoDB返回了一个JSON值。问题是我不想返回与我的返回相关的所有JSON,我尝试搜索文档并且没有找到正确的方法来执行此操作。我想知道如果可能的话,如果是的话,这样做的正确方法是什么。例: 在DB
中{
user: "RMS",
OS: "GNU/HURD",
bearded: "yes",
philosophy: {
software: "FOSS",
cryptology: "Necessary"
},
email: {
responds: "Yes",
address: "rms@gnu.org"
},
facebook: {}
}
{
user: "zuckerburg",
os: "OSX",
bearded: "no",
philosophy: {
software: "OSS",
cryptology: "Optional"
},
email: {},
facebook: {
responds: "Sometimes",
address: "https://www.facebook.com/zuck?fref=ts"
}
}
如果某个字段存在于某个用户,但如果该字段没有返回另一个字段,那么返回该字段的正确方法是什么?对于上面的示例,我想返回RMS的[email][address]
字段和Zuckerburg的[facebook][address]
字段。如果某个字段为空,我试图找到这个,但它似乎没有效果。
.populate('user' , `email.address`)
.exec(function (err, subscription){
var key;
var f;
for(key in subscription){
if(subscription[key].facebook != null ){
console.log("user has fb");
}
}
}
答案 0 :(得分:61)
我并不完全明白你的意思"返回一个字段",但你可以使用lean()
查询,这样你就可以自由地修改输出,然后填充两者字段和后处理结果只保留您想要的字段:
.lean().populate('user', 'email.address facebook.address')
.exec(function (err, subscription){
if (subscription.user.email.address) {
delete subscription.user.facebook;
} else {
delete subscription.user.email;
}
});
答案 1 :(得分:28)
如果您只想为填充的文档返回一些特定字段,则可以通过将字段名称语法作为第二个参数传递给populate方法来完成此操作。
Model
.findOne({ _id: 'bogus' })
.populate('the_field_to_populate', 'name') // only return the Persons name
...
答案 2 :(得分:25)
尝试这样做:
User.find(options, '_id user email facebook').populate('facebook', '_id pos').exec(function (err, users) {
答案 3 :(得分:14)
现在你可以做的是:
.populate('friends', { username: 1, age: 1})
答案 4 :(得分:14)
尝试这样做:
$ terraform apply
ibmcloud_infra_vlan.dev_vlan_01: Creating...
child_resource_count: "" => "<computed>"
datacenter: "" => "FRA02"
name: "" => "pancakes_dev_vlan_01"
router_hostname: "" => "bcr01a.fra02"
softlayer_managed: "" => "<computed>"
subnet_size: "" => "8"
subnets.#: "" => "<computed>"
type: "" => "PRIVATE"
vlan_number: "" => "<computed>"
Error applying plan:
1 error(s) occurred:
* ibmcloud_infra_vlan.dev_vlan_01: 1 error(s) occurred:
* ibmcloud_infra_vlan.dev_vlan_01: unexpected EOF
Terraform does not automatically rollback in the face of errors.
Instead, your Terraform state file has been partially updated with
any resources that successfully completed. Please address the error
above and apply again to incrementally change your infrastructure.
panic: runtime error: invalid memory address or nil pointer dereference
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x17a61bb]
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64:
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: goroutine 68 [running]:
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: github.com/hashicorp/terraform/builtin/providers/ibmcloud.buildVlanProductOrderContainer(0xc4203b00e0, 0xc420392070, 0x1a293c6, 0x20, 0xc420349300, 0x0, 0xc42000e998)
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: /Users/akthakur/git/terraformgo/src/github.com/hashicorp/terraform/builtin/providers/ibmcloud/resource_ibmcloud_infra_vlan.go:386 +0x9fb
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: github.com/hashicorp/terraform/builtin/providers/ibmcloud.resourceIBMCloudInfraVlanCreate(0xc4203b00e0, 0x19b2c00, 0xc4203920e0, 0x0, 0x0)
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: /Users/akthakur/git/terraformgo/src/github.com/hashicorp/terraform/builtin/providers/ibmcloud/resource_ibmcloud_infra_vlan.go:125 +0x20b
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: github.com/hashicorp/terraform/helper/schema.(*Resource).Apply(0xc42036ede0, 0xc420016f50, 0xc420396760, 0x19b2c00, 0xc4203920e0, 0x1, 0x28, 0xc4202adcb0)
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: /Users/akthakur/git/terraformgo/src/github.com/hashicorp/terraform/helper/schema/resource.go:186 +0x48d
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: github.com/hashicorp/terraform/helper/schema.(*Provider).Apply(0xc4202b37a0, 0xc420016f00, 0xc420016f50, 0xc420396760, 0x213b000, 0x0, 0x0)
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: /Users/akthakur/git/terraformgo/src/github.com/hashicorp/terraform/helper/schema/provider.go:242 +0x9b
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: github.com/hashicorp/terraform/plugin.(*ResourceProviderServer).Apply(0xc42034ed80, 0xc4203961c0, 0xc420349260, 0x0, 0x0)
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: /Users/akthakur/git/terraformgo/src/github.com/hashicorp/terraform/plugin/resource_provider.go:488 +0x57
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: reflect.Value.call(0xc42026d6e0, 0xc4202cad40, 0x13, 0x1a0662e, 0x4, 0xc420042f20, 0x3, 0x3, 0x0, 0x0, ...)
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: /usr/local/go/src/reflect/value.go:434 +0x91f
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: reflect.Value.Call(0xc42026d6e0, 0xc4202cad40, 0x13, 0xc4202c4720, 0x3, 0x3, 0x0, 0x0, 0x0)
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: /usr/local/go/src/reflect/value.go:302 +0xa4
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: net/rpc.(*service).call(0xc420362100, 0xc4203620c0, 0xc4203517f8, 0xc4202bb880, 0xc42034f500, 0x182db20, 0xc4203961c0, 0x16, 0x182db60, 0xc420349260, ...)
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: /usr/local/go/src/net/rpc/server.go:387 +0x144
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: created by net/rpc.(*Server).ServeCodec
2017/06/12 16:44:41 [DEBUG] plugin: terraform-provider-ibmcloud_darwin_amd64: /usr/local/go/src/net/rpc/server.go:481 +0x404
2017/06/12 16:44:41 [DEBUG] root: eval: *terraform.EvalWriteState
2017/06/12 16:44:41 [DEBUG] root: eval: *terraform.EvalApplyProvisioners
2017/06/12 16:44:41 [DEBUG] root: eval: *terraform.EvalIf
2017/06/12 16:44:41 [DEBUG] root: eval: *terraform.EvalWriteState
2017/06/12 16:44:41 [DEBUG] root: eval: *terraform.EvalWriteDiff
2017/06/12 16:44:41 [DEBUG] root: eval: *terraform.EvalApplyPost
2017/06/12 16:44:41 [ERROR] root: eval: *terraform.EvalApplyPost, err: 1 error(s) occurred:
* ibmcloud_infra_vlan.dev_vlan_01: unexpected EOF
2017/06/12 16:44:41 [ERROR] root: eval: *terraform.EvalSequence, err: 1 error(s) occurred:
* ibmcloud_infra_vlan.dev_vlan_01: unexpected EOF
2017/06/12 16:44:41 [TRACE] [walkApply] Exiting eval tree: ibmcloud_infra_vlan.dev_vlan_01
2017/06/12 16:44:41 [DEBUG] dag/walk: upstream errored, not walking "provider.ibmcloud (close)"
2017/06/12 16:44:41 [DEBUG] dag/walk: upstream errored, not walking "meta.count-boundary (count boundary fixup)"
2017/06/12 16:44:41 [DEBUG] dag/walk: upstream errored, not walking "root"
2017/06/12 16:44:41 [TRACE] Preserving existing state lineage "91e8972c-40fa-4802-8117-e26fbd21cf8c"
2017/06/12 16:44:41 [TRACE] Preserving existing state lineage "91e8972c-40fa-4802-8117-e26fbd21cf8c"
2017/06/12 16:44:41 [DEBUG] plugin: /Users/mihasya/bin/terraform-provider-ibmcloud_darwin_amd64: plugin process exited
2017/06/12 16:44:41 [DEBUG] plugin: waiting for all plugin processes to complete...
2017/06/12 16:44:41 [WARN] plugin: error closing client during Kill: connection is shut down
答案 5 :(得分:2)
只是为了补充上面的答案,如果您想包括所有内容但仅排除某些属性,则可以执行以下操作:
.populate('users', {password: 0, preferences: 0})
答案 6 :(得分:0)
您可以尝试:
Post.find({_id: {$nin: [info._id]}, tags: {$in: info.tags}}).sort({_id:-1})
.populate('uid','nm')
.populate('tags','nm')
.limit(20).exec();
答案 7 :(得分:0)
您可以在下面尝试使用
Model
.find()
.populate({path: 'foreign_field', ['_id', 'name']}) // only return the Id and Persons name
...
答案 8 :(得分:0)
您好,对我有用吗?我使用填充来填充用户字段 代码:--->
async function displayMessage(req,res,next){
try{
let data= await Msg.find().populate("user","userName userProfileImg","User")
if(data===null) throw "Data couldn ot be loaded server error"
else {
res.status(200).json(data)
}
} catch(err){
next(err)
}
}
我直接得到结果。这里的字段userName,userProfile image是ive选择性地需要的字段,填充的语法是:->
.populate("user field to populate","fields to display with spaces between each of them " , "modelName ")
每个参数都应以逗号分隔。
下面是我收到的输出。您不必担心填充子文档ID的另一件事,您将自动获得它们。
[
{
"_id": "5e8bff324beaaa04701f3bb9",
"text": "testing message route",
"user": {
"_id": "5e8bf062d3c310054cf9f293",
"userName": "boss",
"userProfileImg": "img"
},
"__v": 0
},
{
"_id": "5e8bff8dd4368a2858e8f771",
"text": "testing message route second",
"user": {
"_id": "5e8bf062d3c310054cf9f293",
"userName": "boss",
"userProfileImg": "img"
},
"__v": 0
},
{
"_id": "5e8c0c08e9bdb8209829176a",
"text": "testing message route second",
"user": {
"_id": "5e8bf062d3c310054cf9f293",
"userName": "boss",
"userProfileImg": "img"
},
"__v": 0
},
{
"_id": "5e8c0e0bcb63b12ec875962a",
"text": "testing message route fourth time",
"user": {
"_id": "5e8bf062d3c310054cf9f293",
"userName": "boss",
"userProfileImg": "img"
},
"__v": 0
}
]
答案 9 :(得分:0)
在以下查询中,我检索了符合条件function authClick() {
// Your Client ID is retrieved from your project
//in the Developer Console => https://console.developers.google.com
var CLIENT_ID = 'ClientID';
var SCOPES = ["https://www.googleapis.com/auth/contacts.readonly"];
var APIKEY = 'ApiKey';
gapi.auth.authorize(
{ client_id: CLIENT_ID, scope: SCOPES, apiKey:APIKEY, immediate: false }, authResult);
return false;
}
/**
* Handle response from authorization server.
* @param {Object} authResult Authorization result.
*/
function authResult(_Result)
{
var _Div = document.getElementById('divauthresult');
if (_Result && !_Result.error)
{
$.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + _Result.access_token + "&max-results=500&v=3.0",
function loadPeopleApi()
{
gapi.client.load('https://people.googleapis.com/$discovery/rest',
'v1',
showContacts);
});
}else{
// Auth Error, allowing the user to initiate authorization by
_Div.innerText = ':( Authtentication Error : ' + _Result.error;
}
}
/**
* Load Google People client library. List Contact requested info
*/
/**
* Show Contacts Details display on a table pagesize = 100 connections.
*/
function showContacts()
{
var request =gapi.client.people.people.connections.list({
'resourceName': 'people/me',
'pageSize': 500,
'requestMask.includeField':
'person.phone_numbers,person.organizations,person.email_addresses,person.names'
});
request.execute(function(resp) {
var connections = [resp.connections];
if (connections.length > 0)
{
var _Html = "<table><tr><th>Name</th><th>Email</th><th>Company</th><th>Phone</th></tr>";
var _EmptyCell = "<td id='example' class='table table-striped table-bordered' style='width:100%'> - </td>";
for (i = 0; i < connections.length; i++)
{
var person = [connections[i]];
_Html += "<tr>";
if (person.names && person.names.length > 0)
_Html += "<td>" + person.names[0].displayName + "</td>";
else
_Html += _EmptyCell;
if (person.emailAddresses && person.emailAddresses.length > 0)
_Html += "<td>" + person.emailAddresses[0].value + "</td>";
else
_Html += _EmptyCell;
if (person.organizations && person.organizations.length > 0)
_Html += "<td>" + person.organizations[0].name + "</td>";
else
_Html += _EmptyCell;
if (person.phoneNumbers && person.phoneNumbers.length > 0)
_Html += "<td>" + person.phoneNumbers[0].value + "</td>";
else
_Html += _EmptyCell;
_Html += "</tr>";
}
divtableresult.innerHTML = "Contacts found : <br>" + _Html;
} else {
divtableresult.innerHTML = "";
divauthresult.innerText = "No Contacts found!";
}
});
}
的文章,检索到的数据show=true
也只检索了文章的类别,即类别的标题及其ID。
title and createdAt
答案 10 :(得分:-1)
对于单个级别的填充,您可以使用 -> populate('user','name email age')
用于嵌套种群
populate({
path:'posts',
populate({
path:'user'
select:'name email age'
})
})