【问题标题】:Pushing Objects into MongoDB subdoc array via Mongoose通过 Mongoose 将对象推送到 MongoDB 子文档数组中
【发布时间】:2014-03-09 09:37:33
【问题描述】:

我目前设置了以下猫鼬模型:

var Customer = mongoose.model('Customer', {
    firstname : String,
    lastname : String,
    phone : String,
    street : String,
    city : String,
    state : String,
    zip : String,
    fixed : Boolean,
    readings: [Number]
});

它的使用方式如下:

app.post('/api/findcustomer/:customer_id/:customer_reading', function(req, res) {
    Customer.update({_id: req.params.customer_id},
        {$push: {readings: req.params.customer_reading}},
        {upsert:true},
        function(err, customer){
        if(err){
            console.log(err);
        }else{
            console.log("Successfully added");
        }
    });
    Customer.findOne({
        _id : req.params.customer_id
    }, function(err, customer) {
        if (err)
            res.send(err);
        res.json(customer);
    });
});

目前正在运行。然而,我真正想做的是让读数(在我的模型中)是一个由读数和日期组成的对象数组。我在这方面的最佳尝试包括以下更改:

readings: [{reading: Number, date: String}]

和

{$push: {readings: {reading: req.params.customer_reading, date: 'Some Date'}}}

这对我不起作用,即使我在控制台中成功添加了日志,数组仍然为空。我不确定如何解决这个问题,到目前为止我的搜索还没有产生任何结果。搜索时我的相位可能是错误的,在我请求的情况下读数是否考虑了子文档数组或对象数组,或者只是子文档本身?

任何帮助将不胜感激!

【问题讨论】:

  • 使用 GET 方法来调用更新违反了 REST 的约定。您应该使用 PUT 或至少 POST。
  • 谢谢,是的,我在发帖后发现了这一点。它附带了以前功能的复制粘贴,我忘了更改。将编辑。

标签: javascript node.js mongodb mongoose


【解决方案1】:

呃...看来我的尝试是正确的,但是我试图将读数添加到使用旧模式构建的客户。当我使用 NEW 架构创建了一个新客户并尝试将读取对象添加到它工作的数组时!

【讨论】:

  • 你能解释一下它是如何为你工作的吗?因为我也在尝试做同样的事情,这是我发布的问题 - stackoverflow.com/questions/27510866/…。这里我有子数组,我在其中使用 $push 但它没有产生任何结果。任何帮助将不胜感激和感谢!
猜你喜欢
  • 1970-01-01
  • 2019-03-28
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
相关资源
最近更新 更多