我的问题是为什么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 :(得分:0)
您的update语句需要包含" find"查询。因此,它可以将更新条件应用于与指定查询匹配的所有文档。
将您的代码更改为:
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==);