【问题】

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: 'test@test.com' }, 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. ​


​【答案】 ​

​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. ​