'How to query mongoDB with mongoose without having a model
so i want to query my mongo DB without using a model, let me preface this by saying, i am looking for options other than using the mongodb driver. so in one application i setup the mongoose models and schemas for that database, i am building a seperate application that uses the same database, i was working on authenticating a user when i realized this application will be using credentials stored in that database do i 'need' to define a model just to auth users?
for example in the other application where i defined the models, i would just use the Model.findOne({})
command, but in this application i fail to see the benefits of redefining the model itself, sure i could simply copy/paste the code into the new application and this would work. however im afraid that if i ever need to add/remove fields from the database model in one application that if i fail to update the other, that it could break the application and the data in that application. i've referenced this article here
however this article is a bit dated, and im not connecting to the db and then doing work on it as the top rated answer does, usually i open a connection to the db in my server.js
file and use that connection in other places with the models. but that may not be possible here.
Solution 1:[1]
I've come to find out that Mongo is a schema less database, so if you wanna use mongoose as an abstraction layer to interact with the database, you simply need to define a model and use the setting, strict: false
this will allow you to interact with the database as you were in a normal application where mongoose defines the schema, however i want to point out that you need to be careful using this option, if you are creating a document, and you insert an image
field. but in a different application its expecting a field named imageUrl
then you run into a problem, because it will then create a field image
in your document. this is the beauty of a strict: true
model, if you pass in a field that doesnt meet a mongoose model definition, it ignores it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Austin Howard |