在猫鼬模式中使用ObjectId键和字符串数组作为值定义映射 [英] Defining a map with ObjectId key and array of strings as value in mongoose schema
问题描述
在为数据库创建Mongoose模式时遇到问题.我想创建一个带有objectId作为键和一个字符串值数组作为其值的映射.我能得到的最接近的是:
I'm facing a problem while creating Mongoose schema for my DB. I want to create a map with a objectId as key and an array of string values as its value. The closest that I can get is:
var schema = new Schema({
map: [{myId: {type:mongoose.Schema.Types.ObjectId, ref: 'MyOtherCollection'}, values: [String]}]
});
但是以某种方式,这对我不起作用.当我使用{upsert:true}执行更新时,它没有正确填充映射中的key:值.实际上,我什至不确定我是否正确声明了模式.
But somehow this is not working for me. When I perform an update with {upsert: true}, it is not correctly populating the key: value in the map. In fact, I'm not even sure if I have declared the schema correctly.
有人可以告诉我该架构是否正确吗?另外,如何针对该架构使用{upsert:true}执行更新?
Can anyone tell me if the schema is correct ? Also, How can I perform an update with {upsert: true} for this schema?
此外,如果上述方法不正确并且无法实现,那么我该如何通过其他方式对需求进行建模.我的用例是我想保留给定objectId的值列表.我不希望任何重复的条目具有相同的键,这就是为什么选择了地图.
Also, if above is not correct and can;t be achieved then how can I model my requirement by some other way. My use case is I want to keep a list of values for a given objectId. I don't want any duplicates entries with same key, that's why picked map.
请建议该方法是否正确,还是应该以其他方式建模?
Please suggest if the approach is correct or should this be modelled some other way?
更新:
基于@phillee和此的回答,我只是想知道我们可以修改提到的线程的可接受答案中提到的架构吗,如下所示:
Based on the answer by @phillee and this, I'm just wondering can we modify the schema mentioned in the accepted answer of the mentioned thread like this:
{
"_id" : ObjectId("4f9519d6684c8b1c9e72e367"),
... // other fields
"myId" : {
"4f9519d6684c8b1c9e73e367" : ["a","b","c"],
"4f9519d6684c8b1c9e73e369" : ["a","b"]
}
}
模式将类似于:
var schema = new Schema({
myId: {String: [String]}
});
如果是,我如何相应地更改我的{upsert:true}条件?而且,从复杂度的角度来看,与线程中提到的原始架构相比,它会更简单/复杂吗?
If yes, how can I change my { upsert:true } condition accordingly ? Also, complexity wise will it be more simpler/complex compared to the original schema mentioned in the thread?
推荐答案
我建议更改架构,以便每个myId都有一个条目,
I'd suggest changing the schema so you have one entry per myId,
var schema = new Schema({
myId : {type:mongoose.Schema.Types.ObjectId, ref: 'MyOtherCollection'},
values : [String]
})
如果要更新/更新值,
Model.update({ myId : myId }, { $set : { values : newValues } }, { upsert : true })
这篇关于在猫鼬模式中使用ObjectId键和字符串数组作为值定义映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!