如何在MongoDB / mongoose中使用唯一约束交换docs上的字段?

时间:2015-02-07 12:01:05

标签: node.js mongodb unique

我有系列文档:

[{
    _id: ObjectId(),
    position: 1,
    name: 'This doc'
},
{
    _id: ObjectId(),
    position: 2
    name: 'That doc'
}]

position字段具有唯一约束。此外,我需要它们全部订购,从1到n没有漏洞。

我该如何换掉这些东西?如果我把pos:1放到pos:2而另一种方式,我试着保存,我在第一个doc上得到验证错误。或者当我试图保存整个系列时,它甚至更难(即将doc从pos 7移动到pos 2,后者又从2-6向下移动一个)。

使用MongoDB执行此操作的好策略是什么?并且,最好适用于Mongoose模型或模式?

2 个答案:

答案 0 :(得分:3)

交换<{1}}以外的所有其他字段。

position

答案 1 :(得分:0)

我遇到了在数组中交换文档的类似问题。我使用Mongoose数组“set”函数找到了一个很好的解决方案。以下是Mongoose文档的链接:

http://mongoosejs.com/docs/api.html#types_array_MongooseArray.set

例如,保存在db:

中的文档
{
    "_id" : ObjectId("57a7f57258bf04b578c6ce0c"),
    "name" : "playlist_1",
    "songs" : [
        {
            "artist" : "Brand New",
            "album" : "The Devil and God",
            "title" : "Archers",
            "album_pic" : "29.mp3",
            "song" : "0.jpg",
            "_id" : ObjectId("57a7f62d58bf04b578c6ce0d")
        },
        {
            "artist" : "Modest Mouse",
            "album" : "Lonesome Crowded",
            "title" : "Cowboy Dan",
            "album_pic" : "31.mp3",
            "song" : "30.jpg",
            "_id" : ObjectId("57a7f63c58bf04b578c6ce0e")
        },
        {
            "artist" : "Portugal. The Man",
            "album" : "The Satanic Satanist",
            "title" : "People Say",
            "album_pic" : "33.mp3",
            "song" : "32.jpg",
            "_id" : ObjectId("57a7f65758bf04b578c6ce0f")
        }
    ],
    "__v" : 3
}

以下是在“歌曲”中交换数组项目的功能:

function swapSongs (songIndex1, songIndex2) {
    var playlistName = 'playlist_1',
        swap1,
        swap2;

    //Model called playlist
    Playlist.findOne({name: playlistName}, function (err, playlist) {
        swap1 = playlist.songs[songIndex1];
        swap2 = playlist.songs[songIndex2];
        playlist.songs.set(songIndex1, swap2); //.set(index, newThing)
        playlist.songs.set(songIndex2, swap1);
        playlist.save();
    });
}

以下是swapSongs(0,2);

的结果
{
    "_id" : ObjectId("57a7f57258bf04b578c6ce0c"),
    "name" : "playlist_1",
    "songs" : [
        {
            "artist" : "Portugal. The Man",
            "album" : "The Satanic Satanist",
            "title" : "People Say",
            "album_pic" : "33.mp3",
            "song" : "32.jpg",
            "_id" : ObjectId("57a7f65758bf04b578c6ce0f")
        },
        {
            "artist" : "Modest Mouse",
            "album" : "Lonesome Crowded",
            "title" : "Cowboy Dan",
            "album_pic" : "31.mp3",
            "song" : "30.jpg",
            "_id" : ObjectId("57a7f63c58bf04b578c6ce0e")
        },
        {
            "artist" : "Brand New",
            "album" : "The Devil and God",
            "title" : "Archers",
            "album_pic" : "29.mp3",
            "song" : "0.jpg",
            "_id" : ObjectId("57a7f62d58bf04b578c6ce0d")
        }
    ],
    "__v" : 3
}

希望有所帮助!