尝试将 MongoDB 更新为 jQuery、jQuery UI 可排序和 Express JS

Trying to update MongoDB with jQuery, jQuery UI Sortable, and Express JS

我有一个姓名列表,我想在每次使用 jQuery UI 可排序小部件重新排序后重新提交到 Express 应用程序,然后保存到我的 Mongo数据库。我可以成功地重新排序列表项,数据顺序在我的浏览器控制台中是正确的,但我不知道如何在节点端正确 send/receive 它。如果我对数据数组进行字符串化,整个数组将保存为第一个对象的键,但如果我不对数据进行字符串化,则不会发送任何数据(数据对象为空)。为了简洁起见,这是我的代码缩写:

在我的frontend/jQueryjavascript文件中

$(".favList")
    .sortable({
      connectWith: ".favDetail",
      update: function (event, ui) {
        var lis = $(".favList .favDetail");
        var ids = lis
          .map(function (i, el) {
            return {
              first: el.dataset.first,
              last: el.dataset.last,
            };
          })
          .get();

        var data = JSON.stringify(ids);
        // var data = ids;

        $.ajax({
          type: "POST",
          url: "/people/" + id + "/sortPeople",
          data: data,
        })
          .done(function (response) {
            console.log("OK", data);
          })
          .fail(function (response) {
            console.log("Error", response);
          });
      },
    })
    .disableSelection();

浏览器的控制台日志输出(一切正常):

data: [{id: "5fbf6cdabec1197e4514e7cb", first: "Boba", last: "Fett"},
{id: "5fbf6cdabec1197e4514e7ca", first: "Jango", last: "Fett"},
{id: "5fbf6cdabec1197e4514e7cc", first: "Aurra", last: "Sing"}]

我的 Express JS 控制器和路由器:

const people = await People.findOne({
  _id: req.params.id,
});

await People.findOneAndUpdate(
  { _id: req.params.id },
  { favPeople: req.body },
).exec();

router.route('/:id/sortPeople').post(sortPeople);

我的'People'Mongo模特

const mongoose = require('mongoose');
const peopleSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      trim: true,
      required: true,
    },
    favPeople: [
      {
        id: mongoose.Schema.ObjectId,
        first: String,
        last: String,
      },
    ],
    // favPeople: [],
  },
  {
    timestamps: true,
  },
);

module.exports = mongoose.model('People', peopleSchema);

节点的控制台日志输出: (不对——数组被保存为第一个也是唯一一个对象的键,而不是对象数组):

data: {
 '{"id": "5fbf6cdabec1197e4514e7cb", first: "Boba", last: "Fett"},{"id": "5fbf6cdabec1197e4514e7ca", first: "Jango", last: "Fett"},{"id": "5fbf6cdabec1197e4514e7cc", first: "Aurra", last: "Sing"}': ''
}

如果我不使用 JSON.stringify() 方法,Express 应用程序中不会收到任何内容:(节点的控制台日志输出):

data:  { undefined: [ '', '', '' ] }

我想在 Express 应用程序中接收的是我在浏览器控制台(即)中拥有的相同更新数组:

data: [{id: "5fbf6cdabec1197e4514e7cb", first: "Boba", last: "Fett"},
{id: "5fbf6cdabec1197e4514e7ca", first: "Jango", last: "Fett"},
{id: "5fbf6cdabec1197e4514e7cc", first: "Aurra", last: "Sing"}]

非常感谢任何帮助!谢谢!

我找到了解决办法。要将数据正确传递给控制器​​,必须包含 'dataType' 和 'contentType'。这是我更新的工作代码:

$.ajax({
  type: "POST",
  dataType: "json",
  contentType: "application/json",
  url: "/people/" + id + "/sortPeople",
  data: JSON.stringify(ids),
})