2017-04-04 78 views
0

我正在嘗試構建基於express.js的Node rest API。MongoDB更新很多,如果不存在則創建。 Node API

我有帖子功能正在工作,但我需要更多東西。 現在我送使用郵差數據和我的職務要求是這樣的:

[ 
    { "id": 1, "name": "test", "points": 1}, 
    { "id": 2, "name": "test2", "points": 2}, 
    { "id": 3, "name": "test3", "points": 32}, 
    { "id": 4, "name": "test4", "points": 423}, 
    { "id": 5, "name": "test5", "points": 321} 
] 

這是我的職位功能:

.post(function(req, res) { 

    User.insertMany(req.body) 

     .then(function(mongooseDocuments) { 
      res.json({ message: 'User created!' }); 
     }) 
     .catch(function(err) { 
      /* Error handling */ 
     }); 

}) 

但現在我想更新用戶的點數誰在數據庫中,如果ID(每個用戶都有自己的ID,所以我不能用_id)不存在,我想在此基礎上的模式來創建用戶:

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var UserSchema = new Schema({ 
id: Number, 
name: String, 
points: Number 
}) 

module.exports = mongoose.model('User', UserSchema); 

我設法使用findOneAndUpdate更新一個用戶,但我發送數組元素,我不知道如何處理多個元素。

謝謝

+1

[MongoDB中使用貓鼬大UPSERT]的可能的複製(http://stackoverflow.com/questions/25285232/bulk-upsert-in-mongodb-using-mongoose) –

回答

0

您可以一次迭代並執行一項操作。

下面是使用async.js用於重複一個解決方案。如果你知道如何使用Promise直接循環,你也可以這樣做。

// assuming req.body is an array of all the users 

async.eachSeries(req.body, function upsert (obj, done) { 
    User.findOneAndUpdate({ id: obj.id }, obj, { upsert: true, new: true }, done); 
}, function allDone (err) { 
    if (err) return res.json(err); 
    res.json({ message: 'Users created!' }); 
}); 
+0

謝謝。奇蹟般有效。 – omygoodness

相關問題