Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 views
in Technique[技术] by (71.8m points)

javascript - Mongoose JS findOne always returns null

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...