Mongo关系/引用



我是MongoDB参考的新手。现在我有一个集合,我叫它users。它存储所有用户及其密钥。我有另一个集合,其中包含每个键的数据。

我只想用他们的键作为ID来连接他们。我会生成每个键keyData在第一次创建时是空的然后我会继续向keyData数组添加对象。这是我的计划,但我不知道如何创建与模式的关系。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//Create Schema 
const userKey = new Schema({
_id : {
type : String,
required: true
},
key: {
type : String,
required: true
},
keyData: [key],
date: {
type: Date,
default: Date.now
}
});

module.exports = Key = mongoose.model('key', userKey);

这不起作用,因为在初始化之前我无法访问键。那么我该如何将这两个系列联系起来呢?

Schema #1: userData

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create User-data Schema 
const userData = new Schema({
data: {
type: Array,
require: true
}
},
{
collection: 'data' // Mentioning collection name explicitly is good!
});
module.exports = mongoose.model('data', userData);

Schema #2: Keys

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create User-Key Schema 
const userKey = new Schema({
key: {
type: String,
required: true
},
keyData: { 
type: Schema.Types.ObjectId, 
ref: 'data' 
},
date: {
type: Date,
default: Date.now
}
},
{
collection: 'keys' // Mentioning collection name explicitly is good!
});
module.exports = mongoose.model('keys', userKey);

根据此链接,不可能将string设置为refs。因此,在keys模式中使用ObjectId作为ref

这样的东西会起作用吗?

const userData = new Schema({
_id : {
type : String,
required: true
},
data : {
type : Array,
require: true
}
});
const userKey = new Schema({
_id : {
type : String,
required: true
},
key: {
type : String,
required: true
},
keyData: [{ type: Schema.Types.ObjectId, ref: 'data' }],
date: {
type: Date,
default: Date.now
}
});


module.exports = KeyData = mongoose.model('data', userData);
module.exports = Key = mongoose.model('key', userKey);

最新更新