Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mongoose中带有节点的默认嵌套集合_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js Mongoose中带有节点的默认嵌套集合

Node.js Mongoose中带有节点的默认嵌套集合,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我正在用Node和MongoDB构建一个应用程序,我有一个公司模型和一个API密钥模型,在Mongoose中看起来像这样: var APIKeysSchema = new Schema({ name: { type: String } }); var CompanySchema = new Schema({ name : {type : String, required: true, index: { unique: true }}

我正在用Node和MongoDB构建一个应用程序,我有一个公司模型和一个API密钥模型,在Mongoose中看起来像这样:

  var APIKeysSchema = new Schema({
    name: { type: String }
  });

  var CompanySchema = new Schema({
      name            : {type : String, required: true, index: { unique: true }}
    , apiKeys           : [ APIKeysSchema ]
    , created_at      : {type : Date, default : Date.now}
  });

我希望每个公司在创建公司时默认生成一个API密钥。我应该为此编写自定义中间件,还是在模式本身中有某种方法可以做到这一点。谢谢

最后只是在模型中保存时作为中间件来完成:

CompanySchema.pre('save', function(next){
    if(this.get('apiKeys').length < 1){
        //generate API key
        var objectId = new ObjectID();
        this.get('apiKeys').push({ key: objectId.toHexString() });
    }
    next();
  });
CompanySchema.pre('save',函数(下一步){
if(this.get('apiKeys')。长度<1){
//生成API密钥
var objectId=新objectId();
this.get('apikees').push({key:objectId.toHexString()});
}
next();
});

您是否尝试过为
apikees
添加一个
默认值:
函数来创建您要查找的默认条目?我刚刚添加了MiddleWare,不是每次保存文档时都会向
apikees
添加另一个条目吗?是的……后来意识到了这一点。将其更改为添加检查以查看是否已存在。。。