简体   繁体   中英

Mongoose: presave document with reference

What is the best practice for saving a document with a reference to another collection's document if the _id of that is not immediately available?

var ModelA = new Schema({
  aUniqueIdentifer: String,
  ...
)};

ModelA's aUniqueIdentifier is provided from another datasource, and is used by other models to identify it.

var ModelB = new Schema({
  aUniqueForeignKey: type String,
  aRef : {
    type: mongoose.Schema.Types.ObjectID,
    ref: 'ModelA'
  }
)};

So I might save a modelA: modelA = new ModelA({aUniqueIdentifer: '500'});

Then to save a mobdelB, I need to populate it's aRef with the ModelA object. What is the best practice to do so? Should I do a findOne(aUniqueForeignKey) to return the object before trying to save? This doesn't seem terribly efficient.

I looked into populate, but that seems to be for existing references.

You can use the .pre method to create a method that runs before saving and then put your logic inside that. It looks like this:

ModelB.pre('save', function(next) {
    // Check if id is available
    // if not run another method
    // run next() to exit
    next();
});

This will run before anytime you save ModelB.

Hope this helps, if you add some more information I might be able to provide a more specific solution.

You could try using populate.

Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s)

http://mongoosejs.com/docs/populate.html

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