简体   繁体   中英

Query object in array of subdocuments

Can't formulate right query to find one document (object) in array. Maybe something wrong with schema definition, but I misunderstand. Try methods from similar mongoose topics with no results.

My scheme

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

Tried several ways.

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.

Get result:

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

Expected:

    {
        "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"
    },

Rest code is here https://github.com/akashuba/wineCard-backend/blob/master/saveDbFromJson.js

I don't understand why you tried to put wineProps as an array inside winesSchema . I think your model should be something like this to save wine data.

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

Then you can easily find the document of wine by using findOne() , find() or findById() .

However, if you do not want to change your model structure, you can try as the following example:

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

That value wine will be what you are looking for. Hope this helps your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM