子文档数组中的查询对象

时间:2019-02-13 05:55:17

标签: mongodb mongoose

无法制定正确的查询来在数组中找到一个文档(对象)。 架构定义可能有问题,但是我误会了。 尝试使用类似猫鼬主题的方法,但没有结果。

我的计划

var wineProps = new mongoose.Schema(
    {
        name: String,
        sugarContent: String,
        colorType: String,
        rating: String,
        sparkling: Boolean,
        imgUrl: String,
        colorText: String,
        aromeText: String,
        tasteText: String,
        originText: String,
        priceText: String,
        noteText: String,
        contributor: String
    });

var winesScheme = new mongoose.Schema(
    {
        wines: [wineProps]
    });

exports.Wines = mongoose.model('Wines', winesScheme);

尝试了几种方法。

Wines.find({ "wines": { "$elemMatch": { "_id": "5c625eecde8f72274ca993c8" } } }, function (err, data) {
    if (err) return console.error(err);
    console.log(data);
  })
  Wines.find({ "wines.name": "Toso" }, function (err, data) {...})

Try with findOne.

获取结果:

[ { _id: 5c625eecde8f72274ca993c5,
    wines:
     [ [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object] ],
    __v: 0 } ]

预期:

    {
        "name": "Toso",
        "imgUrl": "http://localhost:3004/img/366toso.jpg",
        "colorType": "red",
        "sugarContent": "",
        "rating": "6",
        "sparkling": false,
        "colorText": "",
        "aromeText": "",
        "tasteText": "",
        "originText": "",
        "priceText": "620",
        "noteText": "",
        "contributor": "Alex"
    },

此处是其余代码https://github.com/akashuba/wineCard-backend/blob/master/saveDbFromJson.js

1 个答案:

答案 0 :(得分:0)

我不明白您为什么尝试将wineProps作为数组放入winesSchema中。我认为您的模型应该像这样保存葡萄酒数据。

var winesScheme = new mongoose.Schema({
    name: String,
    sugarContent: String,
    colorType: String,
    rating: String,
    sparkling: Boolean,
    imgUrl: String,
    colorText: String,
    aromeText: String,
    tasteText: String,
    originText: String,
    priceText: String,
    noteText: String,
    contributor: String
});

exports.Wines = mongoose.model('Wines', winesScheme);

然后,您可以使用findOne()find()findById()轻松找到葡萄酒的文件。

但是,如果您不想更改模型结构,可以尝试以下示例:

Wines.findOne({ "wines.name": "Toso" }, function (err, data) {
    data.wines.forEach(function(wine) {
        if (wine.name == "Toso") {console.log(wine)}
    })
})

该值wine将是您想要的。希望这可以帮助您解决问题。