Defining a map with ObjectId key and array of strings as value in mongoose schema

心已入冬 提交于 2019-12-20 05:35:20

问题


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]}]
});

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.

Can anyone tell me if the schema is correct ? Also, How can I perform an update with {upsert: true} for this schema?

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?

Update:

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"]
    }
}

Schema will be something like:

var schema = new Schema({
   myId: {String: [String]}
});

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?


回答1:


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]
})

If you want to update/upsert values,

Model.update({ myId : myId }, { $set : { values : newValues } }, { upsert : true })


来源:https://stackoverflow.com/questions/32038606/defining-a-map-with-objectid-key-and-array-of-strings-as-value-in-mongoose-schem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!