mongodb 如何使用Mongoose查找数组中的字符串?

gj3fmq9x  于 2023-04-20  发布在  Go
关注(0)|答案(4)|浏览(223)

我通过mongoose有一个模式:

const mongoose = require('mongoose');

const recipeSchema = mongoose.Schema({

title: String,
chef: String,
updated: {type: Date, default: Date.now},
region: String,
ingredients: [String],
instructions: [String]
}, { collection: 'recipes' })

module.exports = mongoose.model('Recipes', recipeSchema);

我发现 Mongoose 文档真的很难理解。我试图在'ingredients'数组中搜索所有子字符串的匹配。我在某个地方读到它可以这样做:

.find({ingredients: 'ing1'}) // not working

 .find({'ing1': {$in: ingredients}})  // not working

我发现在Mongoose上也很难找到深入的教程。我在考虑不再使用它,只坚持使用Mongodb shell。

z6psavjg

z6psavjg1#

可以使用正则表达式搜索来匹配子字符串:

.find({ingredients: /ing1/})
1cosmwyk

1cosmwyk2#

使用mongoose的原因是为了可测试性。
mongoose创建了一个模式,你可以用它来测试你的代码,而不是使用MongoDb示例,在Windows中,使用.lock文件和服务可能会很痛苦。

** Mongoose 方式非常适合TDD/TFD。**

下面是模型和摩卡测试:

recipemodel.js 
    var mongoose = require('mongoose'),Schema=mongoose.Schema;
    var RecipeSchema = new mongoose.Schema({});
    RecipeSchema.statics.create = function (params, callback) {
   '\\ params is any schema that you pass from the test below
      var recipe = new RecipeSchema(params);
      recipe.save(function(err, result) {
        callback(err, result);
      });
      return recipe;
    };
    var recipemodel=mongoose.model('Model', RecipeSchema);
    module.exports = recipemodel;

您不需要描述schema,mongoose会在您通过mocha测试传递集合的值时为您创建schema,例如!

摩卡测试如下:

var mongooseMock = require('mongoose-mock'),
  proxyquire = require('proxyquire'),
  chai = require('chai'),
  expect = chai.expect,
  sinon = require('sinon'),
  sinonChai = require("sinon-chai");
  chai.use(sinonChai);

  describe('Mocksaving a recipe ingredient', function () { 
    var Recipe;
  beforeEach(function () {
    Recipe = proxyquire('./recipemodel', {'mongoose': mongooseMock});
  });

  it('checks if ingredient '+'ing1' + ' saved to mongoose schema', function 
  (done) {
    var callback = sinon.spy();
    var recipe = Recipe.create({ title: "faasos", chef: 
    'faasos',region:'Chennai',ingredients:'ing1',instructions:'abc' }, 
    callback);
    expect(recipe.save).calledOnce;
    expect(recipe.ingredients).equals('ing341');
    done();
    });    
});

对sinon spy的调用只是为了确保对schema中数据的调用被保存(mock saved!),并且'save'方法至少被调用了一次。这个逻辑流程与您的实际逻辑同步,就像您在代码中使用的那样,当对mongodb集合进行保存时。
只需将该值更改为'ing 1',即可在运行测试时使测试通过。
对于数组类型,按如下方式传递值:

var recipe = Recipe.create({ title: "faasos", chef: 
'faasos',region:'Chennai',ingredients:'ing341,ing1',instructions:'abc' }, callback);
    expect(recipe.save).calledOnce;
expect(recipe.ingredients).to.include('ing1');

hc2pp10m

hc2pp10m3#

试试这个:

.ingredients.find((i) => i === "ing1")

对于ingredients数组中的所有元素,它查看内容(这里是字符串元素)是否严格等于“ing1”

t8e9dugd

t8e9dugd4#

你可以用这种方式

.find({ingredients: { $in: [yourIngredients] }});

相关问题