javascript - Understanding upsert with $push -


i have region collection:

var regionschema = new mongoose.schema({   name: {type: string},   registrations: [{type: mongoose.schema.types.objectid, ref: 'registrations'}],   ... }); 

a registration collection:

var registrationschema = mongoose.schema({   firstname: {type: string},   ... }); 

in controller instantiate registration save region upsert option set true:

var registration = new registration(req.body.registration); ... region   .update(     { _id: user.region},     { $push: {registrations: registration},     { upsert: true }   )   .exec(); 

what find objectid("...") does, in fact, pushed onto registrations property of region, e.g.:

{   name: "northwest",   registrations: [objectid("57d038a1466345d52920b194")] } 

but there no matching document _id in registrations collection. question: not understanding nature of upsert flag; not suggest calling save on registration unnecessary?

the upsert flag applies collection you're operating on; in case, region collection. so, when calling region.update, create object _id of user.region if object id doesn't exist.

mongo doesn't enforce strict id references, let push id onto registrations long id valid.

you'll need save registration object first:

var registration = new registration(req.body.registration);  registration.save(function() {   region.update(     { _id: user.region},     { $push: {registrations: registration},     { upsert: true }   )   .exec(); }); 

Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -