findOne返回一个空对象

时间:2018-12-17 23:39:01

标签: node.js mongodb express mongoose orm

我正在尝试通过_id查找和删除子文档,但是它总是返回null。

这是我的User模式:

// Create sub-document schema for items

var itemSchema = new mongoose.Schema ({
  type: String, 
  colour: String, 
  material: String,
  brand: String,
  _id: String,
})

// Main user schema (incl. wardrobe)

const userSchema = new mongoose.Schema({
  email: { type: String, unique: true },
  password: String,
  passwordResetToken: String,
  passwordResetExpires: Date,

  facebook: String,
  twitter: String,
  google: String,
  github: String,
  instagram: String,
  linkedin: String,
  steam: String,
  tokens: Array,

  profile: {
    name: String,
    gender: String,
    location: String,
    website: String,
    picture: String
  },

  wardrobe: {
    items: [[itemSchema]]
  }

}, { timestamps: true });

这是一个示例对象:

{
    "_id": {
        "$oid": "5c16d181c15a68c14fe2f2d3"
    },
    "wardrobe": {
        "items": [
            [
                {
                    "type": "T-shirt",
                    "colour": "Black",
                    "material": "Wool",
                    "brand": "Adidas",
                    "_id": "5c1827dcc13025f86gfdf053"
                }
            ],
            [
                {
                    "type": "T-shirt",
                    "colour": "Black",
                    "material": "Cotton",
                    "brand": "Puma",
                    "_id": "5c1827dfc13025f86dfaf075"
                }
            ]
        ]
    },
    "tokens": [],
    "email": "test@test.com",
    "password": "$2a$10$tyCl4frHgAA1m8p6Y6kAkeAbjdYK1SJ5ghnlvWCF/MAb9.hMfR2/a",
    "createdAt": {
        "$date": "2018-12-16T22:28:17.777Z"
    },
    "updatedAt": {
        "$date": "2018-12-17T23:10:02.301Z"
    },
    "__v": 16,
    "profile": {
        "gender": "",
        "location": "",
        "name": "Test",
        "website": ""
    }
}

这就是我使用findOne的方式:

exports.deleteItem = (req, res, next) => {
    User.findOne({"wardrobe.items._id": "5c1827dfc13025f86dfaf075"}, (err, item) => {
    console.log(item);
    if (err) {
        return console.log("error: " + err);
      }
      res.redirect('/wardrobe');      
    });
  };

console.log(item)始终返回null,即使id字段是现有文档。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

exports.deleteItem = (req, res, next) => {
    User.findOne({"wardrobe.items[0]._id": "5c1827dfc13025f86dfaf075"}, (err, item) => {
    console.log(item);
    if (err) {
        return console.log("error: " + err);
      }
      res.redirect('/wardrobe');      
    });
  };

wardrobe是一个对象,但是items是一个数组,因此您应该放在第一项

答案 1 :(得分:0)

经过反复尝试,结果发现$elemMatch是我所需要的。这将返回整个对象:

exports.deleteItem = (req, res, next) => {
    User.findOne({ 'wardrobe.items': { $elemMatch: { "_id": "5c1985359db5074cb3da562d",} } }, {wardrobe:1}, (err, item) => {
    console.log(item);
    if (err) {
        return console.log("error: " + err);
      }
      res.redirect('/wardrobe');      
    });
  };

但是,我不需要整个对象,而是要搜索带有_id的特定对象。但这是另一个问题。