Home > Software engineering >  Using mongoose, how to add object propety to an object stored in mongodb that is not included in the
Using mongoose, how to add object propety to an object stored in mongodb that is not included in the

Time:05-11

I want to be able to add a new object property to an object in a document stored in a mongodb database where the model schema does not include that property. I've seen all sorts of examples on google and none of them seem to work so I want to ask this question myself and get some direct answers.

For example take this scheme

const MapSchema = new mongoose.Schema({
    name:{
        type: String
    }
})

const ListMap = mongoose.model("listmap", MapSchema);

Now I want to add a new property to it using its id

model.ListMap.findByIdAndUpdate(_id, {newprop:"whatever");

model.ListMap.findByIdAndUpdate(_id, {name:"test");

Using those two commands, I can add name:"test" to it but I can not add newprop:"whatever" to it. What I want to do is be able to add a new property without having to declare it in the schema first. I know this seems like it has been asked before but I've googled it all and I don't believe anyone has answered it. They either didn't understand the question or their code doesn't actually work.

Also bonus question, why does mongodb always add an s to collection names? like the above would show up in collection "listmaps", assuming I used .create() to add the first object.

CodePudding user response:

For your first question, you can not add a property to your schema without declaring it first. you can define a generic property like this:

const MapSchema = new mongoose.Schema({
    property:{
        title: String,
        value: String
    }
})

const ListMap = mongoose.model("listmap", MapSchema);

and for your second question you can refer to this answer: Why does mongoose always add an s to the end of my collection name

CodePudding user response:

-------SOLVED-------------

I am adding this here for others because it was extremely difficult for me to google this. This answer is from another stackexchange link

How to add a new key:value pair to existing sub object of a mongoDB document

based on this, this is how to do what I proposed earlier

const commentMapSchema = new mongoose.Schema({
    List:{}
})

const CommentsMap = mongoose.model("commentmap", commentMapSchema);


const update = {$set: {["List." "test2"] : "data2"}};

CommentsMap.findByIdAndUpdate(id, update);

First you need to declare the property in the schema. This property can hold more properties exactly like how it works with javascript objects. Then use the update method with mongoose with the query that combines the property name with a new property via dot notation. However when adding a property this way, the key must be a string. This works exactly like it does in javascript. You can just create a new name and it'll add to the object properties.

I hope this helps anyone else who landed here.

  • Related