Abdelaziz Mokhnache
Abdelaziz Mokhnache

Reputation: 4349

How to add an other property to a mongoDB found documents using mongoose?

I want to add an extra property state: 'found' to each found document in mongoose. I have the following code:

router.get('/all', function(req, res, next) {
  var allPets = [];

  FoundPet.find({}, function(err, pets) {
    pets = pets.map((obj) => {
      obj.state = 'found';
      return obj;
    })
    res.send(pets)
  })
});

I am expecting to have something like this returned:

[
  {
    "_id": "59c7be569a01ca347006350d",
    "finderId": "59c79570c5362d19e4e64a64",
    "type": "bird",
    "color": "brown",
    "__v": 0,
    "timestamp": 1506291998948,
    "gallery": [],
    "state": "found"  // the added property
  },
  {
    "_id": "59c7c1b55b25781b1c9b3fae",
    "finderId": "59c79a579685a91498bddee5",
    "type": "rodent",
    "color": "brown",
    "__v": 0,
    "timestamp": 1506291998951,
    "gallery": [],
    "state": "found"  // the added property
  }
]

but I can't get the new property added successfully using the above code, is there any solution for that ?

Upvotes: 0

Views: 58

Answers (2)

chridam
chridam

Reputation: 103365

One approach would be to use the aggregation framework in which you can add the extra field using the $addFields pipeline. This allows you to add new fields to documents and the pipeline outputs documents that contain all existing fields from the input documents and newly added fields. Hence you can run the aggregate operation as:

router.get('/all', function(req, res, next) {       
    FoundPet.aggregate([
        { 
            "$addFields": {
                "state": { "$literal": "found" }
            }
        }
    ]).exec((err, pets) => {
        if (err) throw err;
        res.send(pets);
    });
});

Upvotes: 0

m.spyratos
m.spyratos

Reputation: 4219

The reason why it is not working, is because Mongoose by default returns a model for each document returned from the database.

Try the same but using lean(), which returns a plain javascript object instead.

FoundPet
    .find({})
    .lean()
    .exec(function(err, pets) {
        pets.forEach((obj) => {
          obj.state = 'found';
        });
        res.send(pets);
      });

Upvotes: 3

Related Questions