Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  12] [ 1]  / answers: 1 / hits: 23233  / 9 Years ago, sat, february 28, 2015, 12:00:00

I've been fighting with trying to get Mongoose to return data from my local MongoDB instance; I can run the same command in the MongoDB shell and I get results back. I have found a post on stackoverflow that talks about the exact problem I'm having here; I've followed the answers on this post but I still can't seem to get it working. I created a simple project to try and get something simple working and here's the code.



var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
userId: Number,
email: String,
password: String,
firstName: String,
lastName: String,
addresses: [
{
addressTypeId: Number,
address: String,
address2: String,
city: String,
state: String,
zipCode: String
}
],
website: String,
isEmailConfirmed: { type: Boolean, default: false },
isActive: { type: Boolean, default: true },
isLocked: { type: Boolean, default: false },
roles: [{ roleName: String }],
claims: [{ claimName: String, claimValue: String }]
});

var db = mongoose.connect('mongodb://127.0.0.1:27017/personalweb');
var userModel = mongoose.model('user', userSchema);

userModel.findOne({ email: '[email protected]' }, function (error, user) {
console.log(Error: + error);
console.log(User: + user);
});


And here is the response of the 2 console.log statements:



Error: null



User: null



When the connect method is called I see the connection being made to my Mongo instance but when the findOne command is issued nothing appears to happen. If I run the same command through the MongoDB shell I get the user record returned to me. Is there anything I'm doing wrong?



Thanks in advance.


More From » node.js

 Answers
13


Mongoose pluralizes the name of the model as it considers this good practice for a collection of things to be a pluralized name. This means that what you are currently looking for in code it a collection called users and not user as you might expect.



You can override this default behavior by specifying the specific name for the collection you want in the model definition:



var userModel = mongoose.model('user', userSchema, 'user');


The third argument there is the collection name to be used rather than what will be determined based on the model name.


[#67632] Thursday, February 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jovanymarshalld

Total Points: 676
Total Questions: 94
Total Answers: 81

Location: Thailand
Member since Thu, Apr 22, 2021
3 Years ago
;