简体   繁体   中英

Saving Mongoose nested schema

I'm having an issue saving nested subdocs - not sure if its because it's not an array or what - docs seem to suggest that nested objects are auto saved but they are not in this case.

A child schema:

var Address = new Schema({
  phone: String,
  name: String,
  street: { type: String, required: true }
});

Main schema:

var Order = new Schema({
  code: {
    type: String
  },
  address: {
    type: Schema.Types.ObjectId,
    ref: "Address"
  }
});

Neither of these will work.

Create doc doesn't throw errors but subdoc is not saved

var a = new Address({ phone: 000 });

var o = new Order({ address: a }).save();

This gives a Cast to ObjectId failed error:

var o = new Order({ address: { phone: 000 } }).save();

The only way this seems to work is by saving the subdocs first which I'd like to avoid as I have multiple addresses so it's a bit messy.

It's weird that I have never encountered this issue - any ideas?

Ok. Evidently we cannot use subdocs without an array. See SO post Embedded document without Array? and bug thread explaining reasoning: https://github.com/LearnBoost/mongoose/pull/585

The address object in your main schema should be of type Schema.Types.Mixed. You're specifying that address should be an ObjectId, which is why you're getting that Cast to ObjectId error.

See http://mongoosejs.com/docs/schematypes.html .

Example:

var Order = new Schema({
  code: {
    type: String
  },
  address: {
    type: Schema.Types.Mixed,
    ref: "Address"
  }
});

Ok. If you only need a field with sub-fields no other schema needed, you can go this way:

var Order = new Schema({
  code: {
    type: String
  },
  address: {
    phone: String,
    name: String,
    street: { type: String, required: true }
  }
});

To make it save the address schema all you need to do in your function that will save the order is this: var Address = mongoose.model('Address'); var Order = mongoose.model('Order');

export.createAddress =  function( req, res) {
   var address =  new Address({phone: 000});
    address.save(callback function);
};

for the Order schema all you need do is:

export.createOrder =  function( req, res){
   var order = new Order(req.body);
    order.address = req.address;
    order.save(callback function);
}; 

please note this is an example using node, express

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