簡體   English   中英

通過Mongoose將對象推入MongoDB子文檔數組

[英]Pushing Objects into MongoDB subdoc array via Mongoose

我目前已建立以下貓鼬模型:

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'}}}

這對我不起作用,即使我在控制台中成功添加了日志,該陣列仍然為空。 我不確定如何解決該問題,到目前為止,我的搜索沒有得到任何結果。 搜索時我的定相可能是錯誤的,在我要求的情況下,讀數是否被認為是子文檔數組或對象數組,還是僅僅是子文檔本身?

任何幫助,將不勝感激!

......看來我的嘗試是正確的,但是我試圖將讀數添加到使用舊模式構建的客戶中。 當我使用NEW模式創建NEW客戶並嘗試將讀取對象添加到數組時,它起作用了!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM