2012-05-19 10 views
12

L'esempio quiCome posso eseguire il controllo dei tipi in MongoDB?

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

Fornisce il codice seguente

var story1 = new Story({ 
     title: "A man who cooked Nintendo" 
    , _creator: aaron._id 
    }); 

_creator è sopra definito come segue

_creator : { type: Schema.ObjectId, ref: 'Person' } 

Se modifico il codice di seguito

var story1 = new Story({ 
     title: "A man who cooked Nintendo" 
    , _creator: {name: 'test'} 
    }); 

Sembra felicemente inserire i dati in MongoDB.

{ "title" : "A man who cooked Nintendo", "_creator" : { "name" : "test" }, "_id" : ObjectId("4fb7a55315c5f2de07000002"), "fans" : [ ] } 

Come posso rilevare l'errore prima dell'inserimento? Vorrei verificare che non sia solo un ObjectId ma anche che corrisponda ad una Persona valida.

risposta

20

continuare quello @JohnnyHK proposto, ecco una soluzione completa (supponendo _creator è un riferimento ad un id numerico).

Se si desidera controllare se il valore è un ObjectId valida

function isObjectId(n) { 
    return mongoose.Types.ObjectId.isValid(n); 
} 

validate: [validator, 'il mio tipo di errore']

_creator : { type: Schema.ObjectId, ref: 'Person', validate: isObjectId } 
+3

questo dà 'TypeError: Object function ObjectId (chiave, opzioni) {SchemaType.call (this, key, options, 'ObjectID'); } non ha un metodo 'isValid'' – Tom

+6

credo che hanno cambiato in: 'mongoose.Types.ObjectId.isValid()' – herbyme

+0

aggiornate, grazie @herbyme –

1

È possibile aggiungere la convalida al campo _creator dello schema come descritto here.

_creator : { type: Schema.ObjectId, ref: 'Person', validate: ... } 
6

Il metodo isValid non esiste (più?), la tua migliore scommessa è una semplice espressione regolare, come fornito here

+4

credo che hanno cambiato in: 'mongoose.Types.ObjectId.isValid()' – herbyme

Problemi correlati