【发布时间】:2014-10-06 00:24:00
【问题描述】:
在我目前正在构建的 MEAN 应用程序中,客户端向我的 API 发出 $http POST 请求,其中包含特定于该用户的 soundcloud 跟踪数据的 JSON 数组。我现在想要实现的是将这些曲目保存到我的应用程序数据库中的“曲目”表下。这样我就可以从数据库中为该用户加载曲目,还可以创建唯一的客户端 URL (/tracks/:track)
一些示例数据:
{
artist: "Nicole Moudaber"
artwork: "https://i1.sndcdn.com/artworks-000087731284-gevxfm-large.jpg?e76cf77"
source: "soundcloud"
stream: "https://api.soundcloud.com/tracks/162626499/stream.mp3?client_id=7d7e31b7e9ae5dc73586fcd143574550"
title: "In The MOOD - Episode 14"
}
然后将这些数据传递给 API,如下所示:
app.post('/tracks/add/new', function (req, res) {
var newTrack;
for (var i = 0; i < req.body.length; i++) {
newTrack = new tracksTable({
for_user: req.user._id,
title: req.body[i].title,
artist: req.body[i].artist,
artwork: req.body[i].artwork,
source: req.body[i].source,
stream: req.body[i].stream
});
tracksTable.find({'for_user': req.user._id, stream: req.body[i].stream}, function (err, trackTableData) {
if (err)
console.log('MongoDB Error: ' + err);
// stuck here - read below
});
}
});
上面标记的问题是:我需要检查该用户的数据库中是否已经存在该轨道,如果不存在则保存它。然后,一旦循环完成并且所有曲目都已保存或忽略,需要将200 response 发送回我的客户。
到目前为止,我已经尝试了几种方法,但似乎没有任何效果,我真的碰壁了,因此非常感谢您提供有关此方面的帮助/建议。
【问题讨论】:
-
为什么不创建复合索引
db.collection.createIndex( {for_user:1, title:1}, {unique, true} )? -
这将实现什么?
-
它将使您能够仅存储这些索引的唯一组合。如果出现重复,您会收到错误
-
@Bart 我现在不太担心有重复。该应用程序依赖于不断变化的用户 soundcloud 提要,但我想将本地副本保存在我的数据库中。在应用程序决定是否将其保存到数据库之前,我需要检查 soundcloud JSON 中的项目是否已在数据库中。
标签: javascript mongodb express mongoose mean-stack