json - Mongoose 路由特定查询输出

标签 json node.js mongodb express mongoose

Mongoose 新手问题。我正在尝试构建一个 MEAN 应用程序,该应用程序根据用户输入的参数查询现有数据库。外部程序正在使用 JSON 填充数据库。

到目前为止,当我使用以下路由器时,我的路由器成功显示了所有 Mongo 记录:

// Pulls all JSONs
router.get('/jsons', function(req, res, next) {
    Json.find(function(err, jsons){
        if(err) { return next(err);}

        res.json(jsons);
    });
});

现在我正在尝试创建一个单独的路由,它可以显示该数据库中的特定字段。 (其中 TestLocation =“纽约”)

// Pulls a JSON with City New York
router.get('/jsons/NewYork', function(req, res, next) {
    var queryNYC = Json.where({TestLocation: "New York"});
    queryNYC.findOne(function(err, jsons) {
        if(err) { return next(err);}
        res.json(jsons);
    });
});

这向我返回 null,尽管原始路由显示一条 JSON 记录确实具有纽约的 TestLocation。

我的架构如下所示:

var mongoose = require('mongoose');

// Base schema for the query results table
var JsonSchema = new mongoose.Schema({
        uploadID: String,
        uploadDate: Date,
        testDate: Date,
        username: String,
        type: String,
        markers: String,
        image: String,
        TestLocation: String
    },
    {
        collection: 'data'
    }
);

mongoose.model('Json', JsonSchema);

所以我的问题:

A)我的设置是否正确

B) 我是否需要 Mongoose 模式与数据库中的内容完全匹配?我的 Mongoose 模式有一个字段 TestLocation 与 MongoDB 数据库中的 TestLocation 字段匹配,但 MongoDB 数据库中也有很多字段未包含在该模式中。我需要包含这些才能看到此功能吗?

谢谢!

最佳答案

您所做的看起来不错,数据库中的数据不必与您的数据相同。使用以下内容:

Json.findOne({TestLocation: "New York"}, function(err, jsons) {
    if(err) { return next(err);}
    res.json(jsons);
});

关于json - Mongoose 路由特定查询输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28370182/

相关文章:

javascript - Express - 多个数据库连接

c# - 无法使用 C# 驱动程序 1.10 连接到 MongoDB 3.0.0

android - 当 Button onClick 时使用 json 解析设置 TextView

node.js - 将字段添加到从 Mongoose 模式派生的模型中

node.js - 'This' 在 typescript 中未定义,即使在 promise 中使用箭头函数

Mongodb - 如何在多个字段中查找字符串?

java - 带有 Morphia 的 Spring Boot 配置?

javascript - 将项目从 JSON 对象推送到 Angular js 中的下拉列表

java - Gson、Jackson、Flaten Map/HashMap

Javascript - 根据其他 json 值过滤 geojson