带有mongoDB的可排序列表

时间:2016-08-31 21:23:29

标签: javascript mongodb

我想将列表排序并使命令在mongodb中保持不变。每次对列表进行排序时,前端会通过ajax发送一个数组,其中包含按ID更新的项目顺序,例如:

["一些id#","其他一些ID#"等等]

我是mongodb的新手,并且不确定如何相应地更新数据库。到目前为止我在帖子请求中的内容:

//How registered user's credentials are stored via action in redux
  registerUser(username, email, name, password) {
    console.log('Started registering request')
    var user = {
      username: username,
      email: email,
      name: name,
      password: password,
    }

    var request = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(user)
    }

    console.log('Adding user: ', user)

    fetch(`http://localhost:3000/api/users`, request)
    .then(res => res.json())
    .then(user => {
      console.log(user);
      return user;
    })
    .catch(err => {
      console.log('Error is', err)
    })

    console.log('Ending registering request')
  },

Galleryslides是图库架构中包含幻灯片数组的数组。当我运行上面的时候,我得到:

Gallery.findById(req.params.galleryId, function(err, gallery) {
    req.body.ids.forEach(function(id, index) {
        gallery.Galleryslides.update({_id: id}, {sortIndex: index});
    });
    gallery.save(function() {
        res.json({status: 'ok'});
    });
});

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您提到Galleryslides是一个数组,因此没有update方法。

所以它应该是(如果它是一个数组):

gallery.update({'Galleryslides._id': id}, {'$set': {'Galleryslides.$.sortIndex': index}});

如果是嵌入式文档:

gallery.Galleryslides.id(id).sortIndex = index;

如果是关系: 实际上不需要通过父模型。只需按GallerySlide模式更新。

请查看async

async.eachOf(req.body.ids, function(id, index, callback){
  GallerySlide.update({_id: id}, {sortIndex: index}, callback);
}, function(err){
  if(err) return res.json(err);
  res.json({status: 'ok'});
});