I was trying to define a default UUID in mongoose / Node.js / Express for my _id field in my Schema Model...
/**Demonstrator
*
*/
var mongoose = require('mongoose')
var uuid = require('node-uuid')
require('mongoose-uuid2')(mongoose);
var Schema = mongoose.Schema;
require('mongoose-long')(mongoose);
var Status = require('./Status');
var StatusSchema = Status.Schema;
var SchemaTypes = mongoose.Schema.Types;
const uuidv4 = require('uuid/v4');
var UUID = mongoose.Types.UUID;
var DemonstratorSchema = new Schema({
//_id: SchemaTypes.Long;
_id: { type: String, default: uuidv4()},
id2: SchemaTypes.Long,
Test: String,
})
module.exports = mongoose.model("Demonstrator", DemonstratorSchema);
console.log("DemonstratorSchema created!");
I was also trying to write an own function like in this post: Using UUIDs in mongoose for ObjectID references, but this didnt work either... it just won't create a default generated UUID with mongoose in my database, why?
EDIT: I just found out, it creates a UUID or String field with a 32byte UUID value, I just wasn't able to do this in the mongo shell directly, although I thought my Schema kind of enforces this, but its logical that this was nonsense, because the mongo Shell is not aware of anything of my backend constraints ;) sorry about that.... but is it also safe to assume, that anything coming from an REST API endpoint (POST) that is generated and saved in my backend, will have automatically created UUID?
And what is recommended to use as UUID version? v1? or rather v4 or even v5?
The default
property should be a function that returns a string (in your case, a UUIDv4 value).
That's not what your schema provides, though:
_id: { type: String, default: uuidv4()}
That declaration will run the uuidv4
function, which returns a string, and use that string as the default. It's similar to this:
_id: { type: String, default: 'FA6281FF-5961-4F2F-8270-D6AB9954410D'}
Instead, pass it a reference to the uuidv4
function:
_id: { type: String, default: uuidv4 }
That way, each time a default value is required, Mongoose will call that function, which will return a new UUID every time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With