Saturday, 17 August 2013

Mongoose: Find reference documents by id before inserting a doc

Mongoose: Find reference documents by id before inserting a doc

Is there a way for checking if a reference document id exists in the array
field of its "parent" model? Imagine you know the objectId you want to
check if exists because you don't want duplicates and also want to avoid
that an error was thrown when trying to insert it.
I would like to know if there is an elegant and simple way as the method
mongoose provides when working with subdocuments: var doc =
car._components.id(theComponentIdIWantToCheck)
In this case it is a reference document:
Example:
// Car.js
var CarSchema = new Schema({
name: String,
description: String,
_components: [ { type: Schema.Types.ObjectId, ref: 'Component'},]
});

No comments:

Post a Comment