Warm tip: This article is reproduced from serverfault.com, please click

node.js-尝试使用jQuery,jQuery UI Sortable和Express JS更新MongoDB

(node.js - Trying to update MongoDB with jQuery, jQuery UI Sortable, and Express JS)

发布于 2020-11-28 10:14:24

每次使用jQuery UI Sortable Widget重新排序后,我都有要重新提交给Express应用程序的名称列表,然后保存到我的Mongo数据库中。我可以成功地对列表项进行重新排序,在浏览器的控制台中数据顺序是正确的,但是我无法确定如何在节点侧正确地发送/接收它。如果我对数据数组进行字符串化处理,则将整个数组保存为第一个对象的键,但是如果我不对数据进行字符串化处理,则不会发送任何内容(数据对象为空)。为简洁起见,这是我的代码缩写:

在我的前端/ jQuery javascript文件中

$(".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);

我的“人” Mongoose 模型

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应用程序中什么也不会收到:(Node的控制台日志输出):

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

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

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

任何帮助深表感谢!谢谢!

Questioner
user549385
Viewed
11
user549385 2020-11-29 06:59:10

我找到了解决方案。为了将数据正确地传递到控制器,必须包含“ dataType”和“ contentType”。这是我更新的工作代码:

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