Mongoose $在nodeJS

时间:2016-11-19 04:56:09

标签: node.js mongodb mongoose

我创建了一个包含一些操作细节的集合,如下所示

{ "_id" : ObjectId("580776455ecd3b4352705ec4"), "operation_number" : 10, "operation_description" : "SHEARING", "machine" : "GAS CUTT" }
{ "_id" : ObjectId("580776455ecd3b4352705ec5"), "operation_number" : 50, "operation_description" : "EYE ROLLING -1", "machine" : "E-ROLL-1" }
{ "_id" : ObjectId("580776455ecd3b4352705ec6"), "operation_number" : 60, "operation_description" : "EYE ROLLING -2", "machine" : "E-ROLL-1" }
{ "_id" : ObjectId("580776455ecd3b4352705ec7"), "operation_number" : 70, "operation_description" : "EYE REAMING", "machine" : "E-REAM" }
{ "_id" : ObjectId("580776455ecd3b4352705ec8"), "operation_number" : 80, "operation_description" : "COLD CENTER HOLE PUNCHING", "machine" : "C-PNCH-1" }
{ "_id" : ObjectId("580776455ecd3b4352705ec9"), "operation_number" : 150, "operation_description" : "READY FOR HT", "machine" : "RHT" }

使用下面的猫鼬模型

var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var Promise = require("bluebird");

mongoose.Promise = Promise;
var Schema = mongoose.Schema;
var operationSchema = new Schema({
    operation_number: {
        type: String,
        required: [
            true,
            "Please select valid operation code"
        ]unique : true
    },
    operation_description: {
        type: String,
        required: [
            true,
            "Please select valid operation description"
        ]
     }
}, { strict: false });
var operation = mongoose.model('operation', operationSchema);
operationSchema.plugin(uniqueValidator, { message: 'Error, {PATH} {VALUE} already exist.' });


// make this available to our users in our Node applications
module.exports = operation; 

现在,如果我使用operations查询此集合db.operations.find({operation_number : {$in : [10, 50, 60]}}),它可以正常工作,但是当涉及到猫鼬时,它无效。

var mc = require("./data-models/operation")
var filter = {'operation_number': 
                {$in : 
                    [10, 50, 60]
                }
            }
console.log(filter)
mc.find(filter, function(me, md){
    console.log(me, md) // prints null []
})

即使我尝试删除operation_number

周围的单引号

请帮助找到方法!

1 个答案:

答案 0 :(得分:1)

您的架构说operation_number是一个字符串:

operation_number: {
    type: String, <-- here
    ...
}

因此,Mongoose会将$in数组中的数字转换为字符串。

但是,数据库中的数据是数字的,这是一种不同的类型。您应该更改架构,以便operation_number成为Number

operation_number: {
    type: Number,
    ...
}