簡體   English   中英

當架構中存在不存在的字段時,在 mongoose 中查找不返回任何內容

[英]find in mongoose returns nothing when there is a non existing field in the schema

我有一個像這樣的 mongoose 架構:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CitizenSchema = new Schema({
  SSN: {
    type: Number,
    required: true,
    unique: true,
  },
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  }
});

const Citizen = mongoose.model('Citizen', CitizenSchema);

module.exports = Citizen;

我的快遞應用程序中有一條這樣的路線:

router.get('/', (req, res) => {
  if (Object.keys(req.query).length === 0) {
    // Get all the citizens if there is no query
    Citizen.find({})
      .select('-SSN')
      .then((citizens) => res.send(citizens));
  } else {
    const query = req.query;

    // Add case insensitive to all queries
    for (const q in query) {
      query[q] = {
        $regex: new RegExp(query[q], 'i')
      };
    }

    Citizen.find(query)
      .select('-SSN')
      .then((citizens) => res.send(citizens))
      .catch((err) => res.status(400).send({ msg: 'Bad query request' }));
  }
});

所以我所做的是,如果沒有查詢,我返回所有公民,如果有查詢,我返回查詢結果。
例如,如果我使用http://localhost:5000/api/citizens/之類的 GET 請求向我的路線發送 http 請求,我會得到所有公民。 如果我使用http://localhost:5000/api/citizens/?lastName=Doe&firstName=john之類的查詢發送它,我只會得到名字為 John、姓氏為 Doe 的公民。
所以我的問題是,如果我嘗試執行http://localhost:5000/api/citizens/?lastName=Doe&q=test類的請求,我會得到一個空數組,而不是姓氏為 Doe 的公民。 查詢q使得Citizen.find()無法正常工作並且不返回我正在等待的結果。
如果有人能幫我解決這個問題,我將不勝感激。

您可以嘗試在查詢中使用$orhttps://kb.objectrocket.com/mongo-db/or-in-mongoose-1018

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM