本文介绍了Mongoose JS findOne 总是返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力让 Mongoose 从我的本地 MongoDB 实例返回数据;我可以在 MongoDB shell 中运行相同的命令并返回结果.我在 stackoverflow 上找到了一篇关于我遇到的确切问题的帖子 这里;我已经遵循了这篇文章的答案,但我似乎仍然无法让它工作.我创建了一个简单的项目来尝试让一些简单的工作,这是代码.

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);
});

这里是 2 个 console.log 语句的响应:

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

错误:空

用户:空

当调用 connect 方法时,我看到正在连接到我的 Mongo 实例,但是当发出 findOne 命令时,似乎什么也没发生.如果我通过 MongoDB shell 运行相同的命令,则会将用户记录返回给我.我做错了什么吗?

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?

提前致谢.

推荐答案

Mongoose 将模型的名称设为复数,因为它认为将事物集合"作为复数名称的这种良好做法.这意味着您当前在代码中寻找的是一个名为用户"的集合,而不是您所期望的用户".

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.

这篇关于Mongoose JS findOne 总是返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:22
查看更多