【发布时间】:2020-01-22 01:49:04
【问题描述】:
我正在尝试使用 mongoose/nodejs 和 mongoDB 做一个简单的 .find()。我的收藏(显示)中有一个文档(字段为“日期”:“09-20-2019”),但我似乎无法以编程方式找到它。
我尝试使用 MongoDB 指南针(数据库查看器软件)来搜索我要查找的内容。我进入了我的收藏 {date: "09-20-2019"} 下的搜索框,我能够使用他们的搜索功能找到该文档,所以我知道它应该可以工作。我已检查“日期”字段是否作为“09-20-2019”的正确格式和值传递到后端节点服务器。我正在使用 Node.js 10.15.1
--This is from my route.js file
router.get('/shows/:date', (req, res, next)=>{
//res.send('Retrieving the shows list');
console.log('back end date: ' + req.params.date);
Show.find({date: req.params.date}, function(err, result){
if (err)
{
res.json(err);
}
else {
console.log(result);
res.json(result);
}
})
});
--This is from my show.js (mongodb schema file)
const mongoose = require('mongoose');
const ShowSchema = mongoose.Schema({
name:{
type: String,
required: true
},
date:{
type: String,
required: true
},
venue:{
type: String,
required: true
},
createdDate:{
type: String,
required: true
}
});
const Show = module.exports = mongoose.model('Show', ShowSchema);
--This is from my service.ts file
getShow(date)
{
var headers = new Headers();
headers.append('Content-Type', 'application/json');
//date is in format MM/dd/yyyy (e.g. 09-20-2019)
return this.http.get<Show>('http://localhost:3000/api/shows/' + date);
}
--This is from my component
this.commentCardService.getShow(this._date).subscribe(data => {
console.log(data);
});
我希望 .find({}) 操作返回我的 mongoDB 中的单个文档,该文档的日期为“09-20-2019”,这是该集合中目前唯一的文档.集合中最终会存在多个文档。
【问题讨论】:
-
什么是集合名称?和
Shows有区别吗? -
集合名称好像是 Shows。我第一次这样做时,我将新集合手动输入到 mongoDB 指南针中。看起来这可能是问题所在?现在我创建了一个 POST 端点来创建一个“显示”并让它自己创建集合。但是现在我不明白为什么当模式被称为“显示”时集合被称为“显示”?该命名约定从何而来? @SandeepPatel 谢谢
-
第一个参数是您的模型所针对的集合的单数名称。 ** Mongoose 会自动查找您的型号名称的复数、小写版本。请阅读此mongoosejs.com/docs/models.html。如果要覆盖默认模型,可以将第三个参数作为集合名称传递。例如
mongoose.model('ModelName', Schema,collectionName);
标签: node.js mongodb mongoose dao