0

我想爲在貓鼬中找到的每個文檔添加一個額外的屬性state: 'found'。我有以下代碼:如何使用貓鼬將其他屬性添加到mongoDB中查找文檔?

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) 
    }) 
}); 

我期待有這樣的事返回:

[ 
    { 
    "_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 
    } 
] 

,但我不能讓新的屬性添加成功使用上面的代碼,有沒有什麼解決辦法爲了那個原因 ?

回答

3

它不工作的原因是因爲默認情況下,Mongoose會爲從數據庫返回的每個文檔返回一個模型。

嘗試相同,但使用lean(),它會返回一個普通的javascript對象。

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

你不需要使用'陣列#map'這裏,使用'陣列#forEach'代替。 – alexmac

+0

@alexmac,是!還有一些錯誤處理必須完成,但這取決於OP。 –

0

一種方法是使用聚合框架,您可以使用$addFields管道添加額外的領域。這允許您向文檔添加新字段,並且管道輸出包含來自輸​​入文檔和新添加字段的所有現有字段的文檔。 因此,你可以運行的總操作:

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