I’m developing an app in NodeJS with mongoose for mongodb.
For some reasons, I don't define the schema, I just insert into the mongo the whole object that came from another function.
The problem is, when I try to update one object, I can't update one of the fields that is not defined in the schema. I just can update one field that is defined.
For example
var caseSchema = new mongo.Schema({
dhists : String,
dVisible : {'type':'number', default:1}
});
And, to create the object
var DCase = new dcase(data, false);
And then I use the other fields
DCase.dhists = JSON.stringify(hists);
This, in my mongodb has like 20 fields (18 from my source and 2 from my defined schema).
When I try to update one of the 18 fields, it doesn't update. When I try to update one of the other 2 fields (that are defined in the schema) it works.
Is there a way to do this?
Related
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.
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
-------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.
I am new to MongoDB & working on a MEAN application.
In the mongo database(I am using mongoose), the collections are adding dynamically from third party API like schoolList1,schoolList2,schoolList3,schoolList4,....
I am facing problem to find a solution to get data from collections, Like If a user sends the argument from FrontEnd to find data from schoolList3.
The find function should apply on that collection only & return the data.
I am unable to solve it that how should I get data without passing schema and did not get any other way.
Set collection name option for your schema from user's input:
var collectionName = 'schoolList3'; // set value from the input
var dataSchema = new Schema({/** your schema here **/}, { collection: collectionName });
I am trying to convert a string to ObjectId using
var body={};
var objId="57b40595866fdab90268321e";
body.id=mongoose.Types.ObjectId(objId);
myModel.collection.insert(body,function(err,data){
//causing err;
});
the above code is working fine when mongoose 4.4.16 is used, but if i update my mongoose to latest version(4.6.0) then problem occurs.
Err
object [
{
"_bsontype":"ObjectID",
"id:{"0":87,"1":180,"2":5,"3":235,"4":134,"5":111,"6":218,"7":185,"8":2,"9":104,"10":50,"11":111}
}
]
is not a valid ObjectId
The right way to insert new document is-
var newDocument = new myModel({
_id: mongoose.Types.ObjectId("57b40595866fdab90268321e")
});
newDocument.save();
In you case-
It stops working because the differences between versions of mongoose and mongo native drivers.
although, you are able to perform this by the example above, or, if you still want to use insert, you can use the myModel.insertMany (by passing object instead of array)
look here
http://mongoosejs.com/docs/api.html#model_Model.insertMany
I don't have the time to spike it, but if I remember correctly id is a simple string and _id is the ObjectId, i.e. either
body.id="57b40595866fdab90268321e"
or
body._id=mongoose.Types.ObjectId("57b40595866fdab90268321e");
That said, does it have to be that specific id? If not, you can use new myModel() and an id will be automatically created.
In mongoose, I need to find a maximal property value of given model. I have tried dynamically created the mongoose model in a function as
var DynamicSchema=new Schema({id:Number},{collection:collection});
var DynamicModel=mongoose.model('DynamicModel',DynamicSchema);
but after second run of the function I get an error 'OverwriteModelError: Cannot overwrite DynamicModel model once compiled.'
So I tried to create a model in intitialization without setting the collection as
var DynamicSchema = new Schema({id:Number});
var DynamicModel=mongoose.model('DynamicModel',DynamicSchema);
and in a function, tried to set the property collection by
var DynamicModel=mongoose.model('DynamicModel');
DynamicModel.set({collection : collection});
But it does not work. Is there any solution for this situation?
Using mongoose on node.js:
Can I access the _id field on a model before it has been saved to the database and be sure that the ID will not change?
For example, I would like to do the following:
var model = new mongoose.model('MyModel');
someOtherObject.myModelId = String(model._id);
// Some more code...
model.save(...);
In Mongoose, _id values must always be assigned client-side as the docs indicate that:
Mongoose forces the db option forceServerObjectId false and cannot be overridden.
So the model._id value you get in the first line of your code will not be changed unless you do it in your own code before calling model.save.