admin管理员组文章数量:1387304
I'm using nodejs to query mongodb and want to output json with customized field names.
For example, original json from MongoDB maybe
{id:1, text:"abc"}
I'd like to output it as
{ObjectID:1, DisplayText:"abc"};
I understand MongoDB has the $project operator in its aggregate framework but not sure how to use them in NodeJS.
The mongodb nodejs packages I'm using are
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('server:port/mydb');
Appreciate any advice on this.
I'm using nodejs to query mongodb and want to output json with customized field names.
For example, original json from MongoDB maybe
{id:1, text:"abc"}
I'd like to output it as
{ObjectID:1, DisplayText:"abc"};
I understand MongoDB has the $project operator in its aggregate framework but not sure how to use them in NodeJS.
The mongodb nodejs packages I'm using are
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('server:port/mydb');
Appreciate any advice on this.
Share Improve this question edited Jun 23, 2017 at 22:20 Neil Lunn 151k36 gold badges355 silver badges325 bronze badges asked May 30, 2014 at 9:22 LeeLee 3,0423 gold badges31 silver badges59 bronze badges 2- Maybe this will get you started: stackoverflow./questions/16252208/… – John Powell Commented May 30, 2014 at 9:28
- Thanks, John. Would you know which mongodb package to use? I used similar implementation and get TypeError: Object #<Manager> has no method 'collection'. – Lee Commented May 30, 2014 at 9:47
2 Answers
Reset to default 9If you are using monk as you appear to be then you can access the underlying node native driver collection type via the .col
accessor on your selected collection object:
var db = require('monk')('localhost/test')
, collection = db.get('example');
collection.col.aggregate(
[
{ "$project": {
"_id": 0,
"ObjectID": "$_id",
"DisplayText": "$text"
}}
],
function(err,result) {
console.log( JSON.stringify( result, undefined, 4 ) );
}
);
Note that methods such as .aggregate()
retrieved in this way are not wrapped in the promise object as the standard monk collection objects are. But at least this shows you how to access and use $project
to re-shape your document.
Have a look at Virtuals in Mongoose http://mongoosejs./docs/guide.html#virtuals
You could do something like:
someSchema.virtual('text').get(function() {
return this.DisplayText;
}
本文标签:
版权声明:本文标题:javascript - In NodeJS, how to output results from mongodb with different field names? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744558875a2612647.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论