我有系列文档:
[{
_id: ObjectId(),
position: 1,
name: 'This doc'
},
{
_id: ObjectId(),
position: 2
name: 'That doc'
}]
position
字段具有唯一的约束。另外,我需要他们全部订购,从1到n
,没有洞。
我怎样才能交换这些东西呢?如果我把pos:1放到pos:2,反过来,我尝试保存,我在第一个文档上得到验证错误。或者当我试图拯救整个系列剧时,这就更难了。将文档从pos 7移动到pos 2,而pos 2则从2-6向下移动1)。
用MongoDB做这件事的好策略是什么?最好适用于猫鼬模型或模式?
发布于 2015-02-07 14:38:25
交换position
以外的所有其他字段。
var query = {$or:[{position: 1},{position: 2}]};
Schema.find(query, function(err, docs){
Object.keys(docs[0]).forEach(function(key){
if(key=='position') return;
var temp = docs[0][key];
docs[0][key] = docs[1][key];
docs[1][key] = temp;
});
docs[0].save();
docs[1].save();
});
发布于 2016-08-08 03:28:40
我在数组中交换文档时遇到了类似的问题。我找到了一个很好的解决方案,使用Mongoose数组的"set“函数。这里有一个指向Mongoose文档的链接:
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
}
希望这能帮上忙!
https://stackoverflow.com/questions/28381866
复制相似问题