【问题标题】:Meteor SimpleSchema insert with nested object带有嵌套对象的 Meteor SimpleSchema 插入
【发布时间】:2016-02-07 13:54:37
【问题描述】:

我有以下集合,它有一个嵌套对象address,它是使用Collection2 Meteor 包定义的。我无法插入此嵌套对象的数据...

样本数据

var addresses = [{
    "venue": "Kirkstall Abbey",
    "street": "Kirkstall Lane",
    "city": "Leeds",
    "county": "West Yorkshire",
    "postcode": "LS6 3LF"
},{ 
    "venue": "Headingley High School",
    "street": "",
    "city": "Leeds",
    "county": "West Yorkshire",
    "postcode": "LS6 7QR"
}];


var locations = [{
    "name": "Kirkstall Abbey",
    "address": addresses[0],
    "image": null,
    "active": true
},{
    "name": "Headingley",
    "address": addresses[1],
    "image": null,
    "active": true
}];

集合定义

ClassLocation = new Mongo.Collection("class-location");

Schemas.ClassLocation = new SimpleSchema({
    name: {
      type: String,
      optional: true
    },
    address: {
      type: Object
    },
    image: {
      type: String,
      optional: true
    }
    active: {
      type: Boolean,
      optional: true
    }
});

ClassLocation.attachSchema(Schemas.ClassLocation);

例行公事

if(ClassLocation.find().count() === 0) {
  _.each(locations, function (location) {
    console.log(location.address);
    ClassLocation.insert(location);
  });
}

问题

控制台很好地注销了位置地址详细信息对象,但是我的插入文档的 MongoDb 集合对于地址是空的?我尝试了很多方法,包括在初始插入后进行更新(这远非理想)。

谁能解释为什么没有插入这个嵌套对象以及修复它需要什么?

谢谢

【问题讨论】:

    标签: mongodb meteor simple-schema


    【解决方案1】:

    使用 publish-counts 包订阅流星计数:

    // server: publish the current size of a collection
    Meteor.publish('getLocationCounts', function() {
        Counts.publish(this, 'locations-counter', ClassLocation.find());
    });
    

    订阅“getLocationCounts”后,您可以调用Counts.get('locations-counter') 以响应方式获取计数器的值。

    这个函数总是返回一个整数,如果计数器既没有发布也没有订阅,则返回0。

    // client: get the count value reactively
    var exists = (Counts.get('locations-counter')=== 0);
    if(exists) {
        _.each(locations, function (location) {
            console.log(location.address);
            ClassLocation.insert(location);
        });
    }
    

    【讨论】:

    • @chridam...您是如何精通 MongoDB 的?我正在努力成长。我希望我能问你几个问题,聊天之类的。
    • @inspired 主要阅读 MongoDB 的主要文档、博客、JIRA、github,当然还有不断增长的 MongoDB 大学在线课程。给我一个具有相同句柄的 gmail。
    • @chridam 问题不是find().count(),问题是插入的位置地址字段为空(0 个字段)。
    • 我相信问题不在于插入,而在于您如何使用find().count(),这对插入是反应性的。
    • @chridam 我给你发了一封 gmail 邮件。谢谢。
    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2017-02-28
    • 2018-01-21
    相关资源
    最近更新 更多