博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Mongoose JS findOne always returns null
阅读量:6479 次
发布时间:2019-06-23

本文共 2184 字,大约阅读时间需要 7 分钟。

 

【问题】

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.

 

来自:

 

转载地址:http://ulgko.baihongyu.com/

你可能感兴趣的文章
Vijos P1881 闪烁的星星
查看>>
ABP理论学习之领域服务
查看>>
Qt 控制watchdog app hacking
查看>>
让所有IE支持HTML5的解决方案
查看>>
RDD之五:Key-Value型Transformation算子
查看>>
percona 5.7.11root初始密码设置
查看>>
Cognitive Security的异常检测技术
查看>>
Impress.js上手 - 抛开PPT、制作Web 3D幻灯片放映
查看>>
生活杂事--度过十一中秋
查看>>
Pyrex也许是一个好东西
查看>>
WINFORM WPF字体颜色相互转换
查看>>
能力不是仅靠原始积累(三)
查看>>
实战:使用终端服务网关访问终端服务
查看>>
彻底学会使用epoll(一)——ET模式实现分析
查看>>
【Android 基础】Android中全屏或者取消标题栏
查看>>
脱离标准文档流(2)---定位
查看>>
IO流之字符流
查看>>
集合异常之List接口
查看>>
Softmax回归
查看>>
紫书 习题11-11 UVa 1644 (并查集)
查看>>