为什么我的猫鼬findOne查询返回多个结果
我正在设置一条路线,使用findOne和Thing对象ID作为参数,从事物集合中返回特定事物。为什么结果不只返回一个匹配的东西?
我尝试使用id作为参数的findOne
这里是事物架构
const mongoose = require("mongoose");
const thingSchema = mongoose.Schema({
title: { type: String, required: true },
description: { type: String, required: true },
imageUrl: { type: String, required: true },
userId: { type: String, required: true },
price: { type: Number, required: true }
});
module.exports = mongoose.model("Thing", thingSchema);
查找路线
app.get("/api/stuff/:id", (req, res, next) => {
Thing.findOne({
_id: req.params.id
})
.then(thing => {
res.status(200).json(thing);
})
.catch(error => {
res.status(404).json({
error: error
});
});
});
我希望/api/stuff/:5d9834968e23a32580a1751b
的结果是:
{
"_id": "5d9834968e23a32580a1751b",
"title": "tecno camon 8",
"description": "quality condition",
"imageUrl": ".techslize/wp-content /uploads/2017/02/Tecno-camon-c8-black.png?resize=407%2C450&ssl=1",
"price": 3000,
"userId": "userID40282382",
"__v": 0
}
但是实际结果是整个东西集合。
回答如下:如果您通过ID获取数据,那么我建议您使用
Thing.findOne({
_id: req.params.id
})
为什么我的猫鼬findOne查询返回多个结果
我正在设置一条路线,使用findOne和Thing对象ID作为参数,从事物集合中返回特定事物。为什么结果不只返回一个匹配的东西?
我尝试使用id作为参数的findOne
这里是事物架构
const mongoose = require("mongoose");
const thingSchema = mongoose.Schema({
title: { type: String, required: true },
description: { type: String, required: true },
imageUrl: { type: String, required: true },
userId: { type: String, required: true },
price: { type: Number, required: true }
});
module.exports = mongoose.model("Thing", thingSchema);
查找路线
app.get("/api/stuff/:id", (req, res, next) => {
Thing.findOne({
_id: req.params.id
})
.then(thing => {
res.status(200).json(thing);
})
.catch(error => {
res.status(404).json({
error: error
});
});
});
我希望/api/stuff/:5d9834968e23a32580a1751b
的结果是:
{
"_id": "5d9834968e23a32580a1751b",
"title": "tecno camon 8",
"description": "quality condition",
"imageUrl": ".techslize/wp-content /uploads/2017/02/Tecno-camon-c8-black.png?resize=407%2C450&ssl=1",
"price": 3000,
"userId": "userID40282382",
"__v": 0
}
但是实际结果是整个东西集合。
回答如下:如果您通过ID获取数据,那么我建议您使用
Thing.findOne({
_id: req.params.id
})