Mongo / Mongoose检查项目是否存在

时间:2014-08-10 19:52:13

标签: node.js mongodb express mongoose

我很擅长使用Mongo和Mongoose构建大型Web应用程序,我想知道检查项目是否存在的正确方法是什么。

我已经对下面的功能发表了评论,因此我应该很容易理解我正在做的事情以及我遇到的问题。基本上我创造的是:item_exists ? do nothing : save。我目前删除了“保存”#39;因为我不太确定应该放在哪里。

app.post('/tracks/add/new', function (req, res) {

        var newTrack;

        // loop through the objects in req.body
        // item_exists ? do nothing : save

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

            // check if the item already exists by
            // first finding the 'for_user' field and
            // any tracks associated with it (title)

            var query = tracksTable.find({});

            query
                .where('for_user', req.user._id)
                .select('title')
                .exec(function (err, data) {
                    for (var x = 0; x < data.length; x++) {

                        // this is where I've hit a wall...
                        // does 'this' track in the database match
                        // one in the request?

                    }
                });

        }

    });

1 个答案:

答案 0 :(得分:3)

如果您在trackTable集合中寻找一个项目,您可以执行以下操作:

tracksTable.findOne({for_user: req.user._id}, function(err, tracksTableItem) {
    if (err) {
        console.log("MongoDB Error: " + err);
        return false; // or callback
    }
    if (!tracksTableItem) {
        console.log("No item found, creating tracksTable item");

        tracksTable.create(
            {
                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
            }, function(err, createdItem) {
                if (err) {
                    console.log("MongoDB Error: " + err);
                    return null; // or callback
                }
            }
        );
    }
    else {
        console.log("Found one tracksTable item: " + tracksTableItem.for_user);
        // here you could even update your existing item using "tracksTable.save"
    }
    return true; // or callback
}