简体   繁体   中英

Meteor.js & Collection2: Update Method that Inserts New Object in subschema

CONTEXT

I have a collection ("venues"). I'm trying to allow users to add new objects ("rooms" - defined as subschema) to an instance of the venue object. Each room should have an unique id (using autovalue in collection2 schema).

PROBLEM / WHAT I'VE TRIED

I tried two methods:

  1. Venues.insert - attempts to create a new entire Venue instance instead of adding a new row to the roomPricing sub-schema.
  2. Venues.update - using '$set:params" throws an Exception while invoking method 'addRoom' MongoError: Cannot update 'roomPricing' and 'roomPricing.roomId' at the same time . If I remove the Id from the collection, the app updates the 'existing' room values instead of creating a 'new' instance of room.

In summary, I need a method that updates the 'parent' object (the venue) while creating a new 'child' object in the 'room' subschema.

COLLECTIONS

Schema.RoomPricing = new SimpleSchema({
    roomId: {
        type: String,
        autoValue: function(){
             return Random.id();
            },
        optional: true
    },
    roomName: {
        type: String,
        max:50,
        optional: true
      }
    }

// MAIN SCHEMA for the Venues colleciton. 
Schema.Venues = new SimpleSchema({
    venueName: {
        type: String,
        label: "Venue Name",
        max: 200,
        optional: false
},
   roomPricing: {
        type: Schema.RoomPricing,
        optional: true
  }
}

CONTROLLER & METHOD

  var currentVenueId = this.params._id
  var params = {
      roomPricing: {
          roomName: roomName,
          sitCapacity: sitCapacity,
        }
      }

  Meteor.call('addRoom', currentVenueId, params);

//Method
Meteor.methods({
  'addRoom': function (id, params) {
    Venues.insert({
        _id: id
        },{
        $set:params});
        }
    });

In the end this is what I used - needed $push instead of $set.

'addRoom': function (id, params) {
Venues.update({
     _id: id
   },{
     $push:params});
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM