I am using MEAN.io to develop a sample application which registers users and show all registered users. I am able to register a user and log in user, but how can i access all existing users and show them in an html. My exact requirement is,
How can i access existing mongoDB collection in a new model?
I have tried this but didn't work http://stackoverflow.com/questions/5794834/how-to-access-a-preexisting-collection-with-mongoose
Can some one please help me.
Point the mongoose model to the collection you're using using the 3rd argument to mongoose.model()
, then you should be able to use Model.find()
@vkarpov15 I am having somewhat the same problem and I have spent more hours on work around most of the solution I have seen online still not solving my problem.
My problem is I have previously built my app using mongojs and users registered now I am switching to Mongoose and I want to retain my previous registered members and also be able to query the new users but mongoose is returning unknown user for my old user when I query findById.
Please I will be happy with your help thank you.
@devamaz there's nothing preventing you from using mongoose with an existing collection. Here's a few suggestions to troubleshoot your issue:
1) Make sure you're connecting to the same database (mongoose.connect('mongodb://hostname:27017/<db name here>')
) and accessing the same collection (mongoose.model('<model name>', schema, '<collection name here>')
)
2) Make sure your _id
's match your mongoose schemas. If your mongoose schema says _id
is an ObjectId (which it does by default) you should make sure your documents' _id
properties are actually ObjectIds, not strings.
3) findById(id)
is equivalent to findOne({ _id: id })
, so make sure your documents use _id
, not id
.
Is it possible without defining the schema?
@ritwik310 you can just define an empty schema. Mongoose does not cast values coming out of MongoDB, so you should get the whole document back from Model.findOne()
even if you do const Model = mongoose.model('EmptySchema', new Schema({}));
Most helpful comment
@devamaz there's nothing preventing you from using mongoose with an existing collection. Here's a few suggestions to troubleshoot your issue:
1) Make sure you're connecting to the same database (
mongoose.connect('mongodb://hostname:27017/<db name here>')
) and accessing the same collection (mongoose.model('<model name>', schema, '<collection name here>')
)2) Make sure your
_id
's match your mongoose schemas. If your mongoose schema says_id
is an ObjectId (which it does by default) you should make sure your documents'_id
properties are actually ObjectIds, not strings.3)
findById(id)
is equivalent tofindOne({ _id: id })
, so make sure your documents use_id
, notid
.