如何使用mongoose编写与Node.js中的特定字段值匹配的查找查询?

时间:2017-02-04 12:30:35

标签: node.js mongodb mongoose

我使用mongoose在Node JS中定义和操作mongoDB数据库。 我有一个名为' product.js'

的模型架构
var schema = new Schema({
    productName: {
        type: String,
        required: true
    },
    productCategory: {
        type: String,
        required: true
    }
});

每当我需要所有产品时,我都在使用

 var products = Product.find(function (err, docs) { 
        //docs contains all products information
 });

但现在需要获得特定类别的产品。就像我有一个类别名称' cat1'我必须检索所有与' cat1'匹配的产品类别。它主要是,

var products = Product.find({productCategory: 'cat1'}function (err, docs) { 
        //docs contains all products of cat1 category
 });

那么我怎样才能获得所需类别的产品?

1 个答案:

答案 0 :(得分:0)

我在模式中看不到产品和类别之间的任何关系。鉴于Mongoose本身并不提供该功能,您可以放弃传统的SQL实体定义并接受文档存储为您提供的内容:将类别名称/ ID嵌入到产品对象中,以便您可以按照自己的喜好进行查询。

这是使用MongoDB的一大胜利:除了单个值之外,您的文档还可以包含复杂对象。查看包含Person属性的name模型的示例,该属性本身和文档中包含firstlast的对象:

http://mongoosejs.com/docs/queries.html

相关查询

// find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fields
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
  if (err) return handleError(err);
  console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host.
})

请注意'name.last'标准,它会要求Mongo看里面名称属性。

如果您仍想定义单独的产品和类别模型,则必须使用像mongo-relation这样的Mongoose插件。

https://www.npmjs.com/package/mongo-relation