【问题标题】:Save object to array in another model将对象保存到另一个模型中的数组
【发布时间】:2015-12-25 18:24:18
【问题描述】:

所以我得到了两个猫鼬模型:

var mongoose = require('mongoose');
var Schema    = mongoose.Schema;
var eventSchema = new mongoose.Schema({

  name: String,
  date: String,
  dogs: [{ type: Schema.Types.ObjectId, ref: 'Dog' }]

});
module.exports = mongoose.model('Event', eventSchema);

var mongoose = require('mongoose');
var Schema    = mongoose.Schema;
var dogSchema = new mongoose.Schema({

  name: String,
  age: String,
  gender: String,

});
module.exports = mongoose.model('Dog', dogSchema);

Event 包含一个 dogs 数组,我试图弄清楚如何在这个数组中添加/删除狗。

在客户端我得到了这个方法:

  $.ajax({
     url: "http://localhost:3000/api/events/",
     dataType: 'json',
     type: 'POST', // Not sure if I should Post or Put...
     data: {event_Id : this.props.choosenEvent._id, //Here I got the Id of the Event that i want to update by
            dog_Id : this.props.events[dog]._id }, //adding this dog, which Id is here
     success: function(data) {

     }.bind(this),
   });
 },

在服务器 NodeJs 上,我获得了到 API 的路由。对我来说,使用 PUT 方法并首先获取正确的事件并将 event_Id 作为参数传递是有意义的。比如:

router.route('/events/:event_id')
    .put(function(req, res) {


        Event
        .findById({ _id: req.param.event_id })
        .populate('dogs')

        });

但我停留在这一点上。任何帮助表示赞赏。谢谢!

更新!

谢谢!您的代码帮助很大,您使用 lodash .remove 从数组中删除了一条狗,是否有类似的方法可以使用 lodash 添加项目?

我给了 add 方法一个这样的例子:

router.route('/events')   
      .post(function(req, res) {
          // Your data is inside req.body

          Event
              .findById({ _id: req.body.event_Id })
              // execute the query
              .exec(function(err, eventData) {
                  // Do some error handing
                  // Your dogs are inside eventData.dogs
                  eventData.dogs.push(req.body.dog_Id);
                  console.log(eventData)

                });
                  // Update your eventDate here
                  Event.update({_id: req.body.event_id}, eventData)
                      .exec(function(err, update) {
                          // Do some error handing
                          // And send your response
                      });
              });

当我点击console.log(eventData) 时,我可以看到dog_id 已按应有的方式添加到数组中。但是它不会保存到数据库中,并且错误表明eventData 未在Event.Update 中定义。我怀疑这是一个 Js-scope-issue。

让我感到困惑的是:

显然我希望能够在数组中添加和删除狗,并且 路线是这样的:router.route('/events')

但是如果add-method和remove-method都在同一个路由上,那代码怎么知道我要去哪一个呢?

【问题讨论】:

    标签: javascript ajax node.js mongoose reactjs


    【解决方案1】:

    您犯了一些错误。首先,您正在发出 POST 请求,但您的路由接受 PUT 请求。我已经更新了您的代码,因此它可以接受 POST。

    发布对象时,您的数据位于 req.body 中。 req.params 用于 url 参数。使用 PUT 请求时也是如此。

    填充并不是真正必要的。您将 dog_id 发送到您的函数,以便您可以从数组中删除您的项目,从而将您的狗从您的活动中移除。这应该可以解决问题。请注意,这不会将您的狗从您的数据库中删除,而只会从您的活动中删除。

    最后但并非最不重要。我正在使用lodash_.remove 是一个 lodash 函数。你一定要看看它,它会对你有很大帮助。

    看看我的代码。它应该能让你前进:

    router.route('/events/:event_id')
        // Since you are posting, you should use POST from JavaScript instead of PUT
        .post(function(req, res) {
            // Your data is inside req.body
            Event
                .findById({ _id: req.body.event_id })
                // execute the query
                .exec(function(err, eventData) {
                    // Do some error handing
                    // Your dogs are inside eventData.dogs
                    _.remove(eventData.dogs, function(d) {
                        return d._id === req.body.dog_Id;
                    });
                    // Update your eventDate here
                    Event.update({_id: req.body.event_id}, eventData)
                        .exec(function(err, update) {
                            // Do some error handing
                            // And send your response
                        });
                });
    
            });
    

    更新

    我认为没有办法使用 lodash 将项目添加到数组中,但您可以像在代码示例中那样简单地使用 push。效果很好。

    您的更新不起作用,因为您正在同时执行 findById 和更新。您必须先找到该项目,添加 id,然后更新该项目 :) 将您的更新函数移动到您的 findById 函数的回调中,这应该是固定的。所以它看起来像这样:

    router.route('/events')   
        .post(function(req, res) {
            // Your data is inside req.body
    
            Event
            .findById({ _id: req.body.event_Id })
            // execute the query
            .exec(function(err, eventData) {
                // Do some error handing
                // Your dogs are inside eventData.dogs
                eventData.dogs.push(req.body.dog_Id);
                console.log(eventData)
    
                // Update your eventDate here
                Event.update({_id: req.body.event_id}, eventData)
                .exec(function(err, update) {
                    // Do some error handing
                    // And send your response
                });
            });
        });
    

    您可以在同一条路线上添加不同的功能,只要方法与其他方法不同即可。在answer 上查看 REST。您可以在 /events 上设置 GETPOSTPUTDELETE。这是由以下规则定义的:

    router.route('/events').post();
    

    【讨论】:

    • 非常感谢!你肯定让我走上正轨。如果可以,请查看更新。
    • 非常感谢!这篇文章对我来说会派上用场很多次。
    猜你喜欢
    • 1970-01-01
    • 2019-06-23
    • 2022-10-14
    • 1970-01-01
    • 2018-05-05
    • 2015-02-27
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    相关资源
    最近更新 更多