2017-01-16 127 views
0

這裏我的問題是爲什麼watchlistSchema.update(function (error) { { $push: { watchlist: req.body.stockAdded } }});行不更新watchlist屬性的現有模式?當我使用這個更新時,沒有任何反應,它返回null。當我將其更改爲watchlistSchema.save時,它可以正常工作,但會創建完全不同的文檔。我想基本上檢查用戶和監視列表,如果他們都存在在一起,我想推入一個字符串到監視列表數組。我對貓鼬很陌生,所以有點混淆。貓鼬更新不起作用

var Schema = mongoose.Schema;  

var watchlistSchema = new Schema({ 
    watchlist: [{ }], 
    user: String 
}); 

var Watchlist = mongoose.model('Watchlist', watchlistSchema, "watchlist");  

app.post('/watchlistPost', function (req, res) { 

var watchlistSchema = Watchlist({ 
    'watchlist': req.body.stockAdded, 
    'user': req.user.username 
}); 

Watchlist.findOne({ 
    $and: [{ 
     'watchlist': req.body.stockAdded, 
    }, { 
     'user': req.user.username 
    }] 
}, function (err, list) { 
    if (list) { 
     res.status(200).send({ "success": "Updated Successfully", "status": 200 }); 
    } else { 
     if (req.user) { 
      watchlistSchema.update(function (error) { 
       { $push: { watchlist: req.body.stockAdded } } 
      }); 
     } else { 

     } 
    } 
}) 
}); 

回答

0

您的update語句需要包含「查找」查詢。因此它可以將更新條件應用於與指定查詢匹配的所有文檔。

更改您的代碼是這樣的:

var Schema = mongoose.Schema;  

var watchlistSchema = new Schema({ 
    watchlist: [{ }], 
    user: String 
}); 

var Watchlist = mongoose.model('Watchlist', watchlistSchema, "watchlist");  

app.post('/watchlistPost', function (req, res) { 

var watchlistSchema = Watchlist({ 
    'watchlist': req.body.stockAdded, 
    'user': req.user.username 
}); 

var query = { 
    $and: [{ 
     'watchlist': req.body.stockAdded, 
    }, { 
     'user': req.user.username 
    }]}; 

Watchlist.update(query, { $push: { watchlist: req.body.stockAdded } }, ==your callback to check stuff==);