[英]MongoDB - findOne using the params id results in an empty object or an error
I'm learning Express/Mongo(using mLab) by building a simple little app that I can create a list of clients and a single client detail page. 我正在通过构建一个简单的小应用程序来学习Express / Mongo(使用mLab),该应用程序可以创建客户列表和单个客户详细信息页面。
localhost:3000/clients renders the entire collection of ' clients ' localhost:3000 / clients呈现“ 客户端 ”的整个集合
localhost:3000/clients/:id should render the specific client by id localhost:3000 / clients /:id应该通过id呈现特定的客户端
This is a collection: clients entry example from MongoDB (mLab): 这是一个集合:来自MongoDB(mLab)的客户端输入示例:
{
"_id": {
"$oid": "57ba01d3ab462a0aeec66646"
},
"name": "ClientName",
"address": {
"street": "StreetName",
"city": "Cityname",
"state": "Statename",
"zip": "1234"
},
"createDate": {
"$date": "2016-08-21T19:32:35.525Z"
}
}
I successfully created an href on the /clients page with the id value that links to the specific client: 我在/ clients页面上成功创建了一个href,其id值链接到特定的客户端:
<a href="/clients/<%= client._id %>"><%= client.name %></a>
Which correctly results in this: 正确地导致以下结果:
http://localhost:3000/clients/57ba01d3ab462a0aeec66646
Here is my get function for /clients/:id : 这是我的/ clients /:id的 get函数:
app.get('/clients/:id', (req, res) => {
db.collection('clients').findOne(req.params.id, (err, result) => {
if (err) {
handleError(res, err.message, "Failed to get clients.");
} else {
console.log(result);
res.render('client.ejs', {client: result})
}
});
})
Clicking on the link results in the following error: 单击链接将导致以下错误:
MongoError: query selector must be an object at Function.MongoError.create (/Users/username/Desktop/node/node_modules/mongodb-core/lib/error.js:31:11) at Collection.find [...]
MongoError:查询选择器必须是Function.MongoError.create(/Users/username/Desktop/node/node_modules/mongodb-core/lib/error.js:31:11)处的对象。
I've been reading and searching all afternoon and trying a ton of different options like: 我整个下午一直在阅读和搜索,并尝试了大量不同的选择,例如:
Do I really need Mongoose? 我真的需要猫鼬吗? This seems like a foundational thing to do it Mongo — why isn't it working?
这似乎是Mongo的基础工作-为什么它不起作用?
you need to use an object : {id: req.params.id}
您需要使用一个对象:
{id: req.params.id}
app.get('/clients/:id', (req, res) => {
db.collection('clients').findOne({_id: req.params.id}, (err, result) => {
if (err) {
handleError(res, err.message, "Failed to get clients.");
} else {
console.log(result);
res.render('client.ejs', {client: result})
}
});
})
You need to convert req.params.id to MongoObject and then use it: 您需要将req.params.id转换为MongoObject,然后使用它:
var id = new ObjectID(req.params.id); var id = new ObjectID(req.params.id);
也许像这样:
db.collection('clients').findOne({"_id.$oid": req.params.id}, (err, result) =>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.