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

时间:2018-02-24 17:37:21

标签: mongodb mongoose

我有一个通过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文档真的很难理解。我正在尝试搜索'成分中所有子串的匹配。阵列。我在某处读到可以这样做:

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

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

我发现很难找到关于mongoose的深度教程。我想不再使用它,只是坚持mongodb shell。

3 个答案:

答案 0 :(得分:1)

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

.find({ingredients: /ing1/})

答案 1 :(得分:0)

使用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;

您不需要描述架构,例如,当你从mocha测试中传递集合的值时,mongoose会为你创建它!

摩卡测试如下:

  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();
    });    
});

mocha test result

对sinon间谍的调用只是为了确保对模式中数据的调用得到保存(模拟保存!)以及“保存”。方法确实被调用了至少一次。当你在mongodb集合上进行保存时,这个逻辑流程就像你在代码中使用的那样与你的实际逻辑同步。

只需将值更改为' ing1'在运行测试时通过测试。

对于数组类型,传递如下值:

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');

mocha test for values passed to schema as an array

答案 2 :(得分:0)

尝试一下:

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

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