MongooseJS - 如何推送正确的格式?

时间:2016-10-27 06:17:09

标签: node.js mongodb express mongoose

我想以这种格式创建数据:

{
    "weather": {
        "dailysummary": [...],
        "created_on": "2016-10-27 11:11:11",
        "addedOnLastHour": false
    }
}

但为什么moongoose一直给我这种格式:

{
    "weather": [
        {
        "dailysummary": [...],
        "created_on": "2016-10-27 11:11:11",
        "addedOnLastHour": false
        }
    ]
}

我的代码:

var updateQuery = {};
var weather = {};
weather.dailysummary = [];
weather.created_on = '2016-10-27 11:11:11';
weather.addedOnLastHour = false;

// Insert date data.
updateQuery["weather"] = weather;

stream.update({
    $push: updateQuery
}, function(err, streamID) {
    if (err) {
        // handle error
    }
    // success
});

我做错了什么?有什么想法吗?

我的模特:

var mongoose = require("mongoose");
var mongoosePaginate = require('mongoose-paginate');

// Declare schema
var streamSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    weather: {
        type: Object
    },
});

streamSchema.plugin(mongoosePaginate);

// Export schema
// Model.paginate()
mongoose.model("Stream", streamSchema);

2 个答案:

答案 0 :(得分:2)

您可以使用 $ set 运算符代替 $ push

试试这个:

stream.update({
    $set: updateQuery
}, function(err, streamID) {
    if (err) {
        // handle error
    }
    // success
});

答案 1 :(得分:1)

$ push 似乎是问题的制造者。它用于将对象推送到数组数据类型属性。因此,你正在获得一系列的天气。以下是mongoose中更新的示例代码段。

Contact.update({_id: contact.id}, weatherObject, {}, function() {});

下面:

联络 - >模型

Where子句 - > {_id:contact.id}

weatherObject - >更新数据