简体   繁体   English

每次使用`new mongoose.Schema`都会使用相同的默认值

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

I have problem using uuid with new mongoose.Schema . 我有问题使用new mongoose.Schema uuid I use it to generate unique key for a device and save it to the MongoDb using Node.js. 我使用它为设备生成唯一键,并使用Node.js将其保存到MongoDb。 the problem is that it uses the same UUID every time. 问题是它每次都使用相同的UUID。

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: 这是MongoDb中保存的内容: 在此输入图像描述

Any idea what's wrong? 知道什么是错的吗?

You're calling uuid and passing its return value in as the default to use. 您正在调用 uuid并将其返回值作为默认值使用。

Instead, pass in the function (by not putting () after it): 相反,传入函数 (通过不在其后put () ):

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). 默认值可以是每个文档的一个函数(例如,使用default: Date.now为日期字段提供默认值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM