【问题标题】:How to query mongoose by property that is and array item如何通过属性和数组项查询猫鼬
【发布时间】:2013-05-06 00:12:03
【问题描述】:

我有一个看起来像这样的猫鼬模型:

var mongoose = require('mongoose')
, Schema = mongoose.Schema;

var PictureSchema = new Schema({
    listId: { type: Array, required: true },
    thumb: { type: String, required: true },
    large: { type: String, required: true }
});

var Picture = module.exports = mongoose.model('Picture', PictureSchema);

我正在尝试通过“listId”属性查找图片来更新路由器中此模型的实例。像这样:

app.put('/pictures/append', function(req, res) {
  var targetListId = req.body.targetListId
    , currentListId = req.body.currentListId;

  Picture
    .find({ listId: currentListId }, function (err, picture) {
      console.log('found pic', picture);
      picture.listId.push(targetListId);
      picture.save(function(err, pic) {
        console.log('pic SAVED', pic);
      });
    });
});

“currentListId”是一个字符串,listId 是一个 currentListId 的数组。也许这不是查询作为数组的属性的正确方法? 我收到一个错误:

TypeError: Cannot call method 'push' of undefined

上线:

picture.listId.push(targetListId);

但是当我在 mongo 中查找图片模型时,它们确实有 listId 数组,并且有些确实包含我用于查询的项目“currentListId”。

我尝试使用 $elemMatch 和 $in 但我不知道我是否正确使用它们。 知道我只是写错了查询吗?

【问题讨论】:

    标签: arrays node.js mongodb mongoose


    【解决方案1】:

    在你的模式中指定一个Array 类型字段等同于Mixed,它告诉Mongoose 该字段可以包含任何内容。相反,将您的架构更改为以下内容:

    var PictureSchema = new Schema({
        listId: [String],
        thumb: { type: String, required: true },
        large: { type: String, required: true }
    });
    

    【讨论】:

    • 非常感谢,这解决了我的问题。我还需要像这样调整我的路由器更新代码:.update({ listId: { $in: [currentListId] } }, {$push: {'listId' : targetListId } }, { multi: true }, function (err, data) { console.log('Updated', data); });
    • @nicki9knuckles 太好了,欢迎来到 SO。如果您的问题得到解决,您可以点击答案左侧的复选标记。
    猜你喜欢
    • 2019-07-12
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多