最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - In NodeJS, how to output results from mongodb with different field names? - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 9

If 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;
}
发布评论

评论列表(0)

  1. 暂无评论