为什么这个数组字段查询在Mongoose中失败但在Mongo shell中失败?

时间:2016-09-07 18:24:11

标签: node.js mongodb mongoose

这是我在Mongoose中的User架构。

var userSchema = mongoose.Schema({
    username: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    mobile: {
        type: Number,
        required: true
    },
    accounts: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Account'
    }]
});

var User = mongoose.model('User', userSchema);

在mongo shell中,它会找到我现有的用户文档:

db.users.find({ accounts:"57d03b30edfd30e806fb20c9"})

但是使用Mongoose,它会找到空集:

User.find({ accounts: "57d03b30edfd30e806fb20c9" })
    .exec(function (err, users) {

       *** users == [] ***

    });

2 个答案:

答案 0 :(得分:1)

User.find({ accounts: mongoose.Types.ObjectId("57d03b30edfd30e806fb20c9") })

或者......

var ObjectId = mongoose.Types.ObjectId;
User.find({ accounts: ObjectId("57d03b30edfd30e806fb20c9") })

正如@ vdj4y所提到的,Mongoose将您的查询解释为String而不是ObjectId(我想是它?)

答案 1 :(得分:0)

实际上,如果架构匹配,则应将ObjectId视为字符串

accounts: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Account'
}]

然后查询它就像是一个字符串

User.find({ accounts: "57d03b30edfd30e806fb20c9" })
.exec(function (err, users) {

   *** users == [] ***

});

但您需要删除上一个条目,因为它当前是“混合”类型。我猜混合实际上只是一个字符串,所以你可以尝试使用类似下面的字符串类型。好吧,您可以在mongoshell中查询字符串并查找结果

  accounts: [{
    type: mongoose.Schema.Types.String,
    ref: 'Account'
}]