我试图使用Express.js + Mongoose在Node.js中的MongoDB中返回集合的值。要使用的客户端期望的数据格式与我的格式不同。返回的数据应该是这样的:
[{ “ userId”:1 “ id”:1 “ title”:“某些标题”, “身体”:“某个身体” },{ “ userId”:1 “ id”:2 “ title”:“另一个标题”, “ body”:“另一个身体” },...
但是,我的服务返回的json具有集合名称(在我的示例中为flavors)作为json中的第一个元素,如下所示:
{“风味”:[{“ _ id”:“ 5b818da7fb6fc0183b40ea50”,“名称”:“名称”,“种类”:“ a kind”},{“ _ id”:“ 5b818dd8fb6fc0183b40ea5b”,“名称”: “另一个名称”,“种类”:“另一个种类”},...
那是我的代码:
...
import Flavor from "../models/flavors";
...
const router = express.Router();
router.options("/", (req, res) => {
Flavor.find().then(result => {
res.json({ result });
}).catch((err) => {
res.status(500).json({ success: false, msg: `Something went wrong. ${err}` });
});
});
在模型中添加模型/风味:
import mongoose, { Schema } from "mongoose";
const schema = new Schema(
{
name: String,
kind: String,
});
export default mongoose.model("flavors", schema);
那么,如何在获取结果中消除这种风味(集合名称)?
答案 0 :(得分:0)
我找到了答案。错误在于代码的这一部分中res.json内的花括号中:
router.options("/", (req, res) => {
Flavor.find().then(result => {
res.json({ result });
}).catch((err) => {
res.status(500).json({ success: false, msg: `Something wrong. ${err}` });});});`
因此,如果以这种方式使用它:
res.json({ result });
mongo / mongoose的集合名称将首先显示。当我更改为这种方式时:
res.json(result);
收藏名称消失了。