猫鼬查询返回null [英] Mongoose query return null

查看:64
本文介绍了猫鼬查询返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法从mongodb得到答复.我在mongoose的帮助下使用node.js和mongodb.

I can't seem to get a response from mongodb. I am using node.js and mongodb with the help of mongoose.

在我的node.js应用中,

In my node.js app I have

mongoose.connect('mongodb://localhost:27017/myDB');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var BlogPost = new Schema({
    author  : ObjectId,
    title   : String,
    slug    : { type: String, lowercase: true, trim: true },
    content : String,
    summary : String,
    date    : Date
})

var BlogModel = mongoose.model('BlogPost', BlogPost);

BlogModel.find({}, function(docs){
   console.log(docs);
});

如果我在mongo shell中输入show dbs,我会得到

If I type show dbs in the mongo shell I get

admin   (empty)
myDB       0.203125GB
local   (empty)
test    (empty)

db.blogmodel.find()返回:

db.blogmodel.find() returns :

{ "_id" : ObjectId("50108d3df57b0e3375a20479"), "title" : "FirstPost" }

是的,我确实有mongod在运行.

and yes I do have mongod running.

固定解决方案

var BlogModel = mongoose.model('blogmodel', BlogPost, 'blogmodel');

它之所以有效,是因为它的(模型名称,架构名称,集合名称)

It works because its (model name, schema name, collection name)

推荐答案

猫鼬将模型名称复数,因此它在"blogposts"集合而不是"blogpost"上运行find.就是说,您在mongo shell中的查询在"blogmodel"集合上.在这种情况下:

Mongoose pluralizes model names so it's running find on the "blogposts" collection instead of "blogpost". That said, your query in the mongo shell is on the "blogmodel" collection. In that case:

var BlogModel = mongoose.Model("BlogModel", ..)

或将集合名称作为第三个参数传递:

or pass the collection name as the third param:

var BlogModel = mongoose.model("BlogPost", schema, "blogmodel")

这篇关于猫鼬查询返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆