简体   繁体   中英

The same default value gets used every time by `new mongoose.Schema`

I have problem using uuid with new mongoose.Schema . I use it to generate unique key for a device and save it to the MongoDb using Node.js. the problem is that it uses the same UUID every time.

This is the model:

const mongoose = require('mongoose');
const uuid = require('uuid/v4');

const DeviceSchema = new mongoose.Schema({
    deviceNumberHash: {
        type: String,
        required: true
    },
    receivingKey: {
        type: String,
        default: uuid()
    }...
});

And this is what is saved in MongoDb: 在此输入图像描述

Any idea what's wrong?

You're calling uuid and passing its return value in as the default to use.

Instead, pass in the function (by not putting () after it):

const DeviceSchema = new mongoose.Schema({
    deviceNumberHash: {
        type: String,
        required: true
    },
    receivingKey: {
        type: String,
        default: uuid // <========== No ()
    }...
});

The default can be a function per the docs (an example there uses default: Date.now to provide a default for a date field, for instance).

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