node.js - Mongoose $in 无法在 NodeJS 中工作

标签 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" }

使用 Mongoose 模型如下

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; 

现在,如果我使用db.operations.find({operation_number : {$in : [10, 50, 60]}})查询这个集合operations,它就可以工作但当涉及到 Mongoose 时,它就不起作用了。

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 周围的单引号

请帮忙寻找方法!

最佳答案

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

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

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

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

operation_number: {
    type: Number,
    ...
}

关于node.js - Mongoose $in 无法在 NodeJS 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40689363/

相关文章:

javascript - Sails.js ,从 Controller 调用路由

用于 Erlang 的 MongoDB 驱动程序

javascript - 模型之间的 Mongoose 关系

node.js - 非索引字段上的索引重复键

javascript - 如果所有数据库操作都通过 Mongoose 完成,注入(inject)仍然是一个问题吗?

node.js - 在 mongoose Schema 文件 Nestjs 中使用进程 env

node.js - Angular.js 可以在脚本标签中的 Jade 模板中进行插值吗?

javascript - Nodejs,如何重构数据的响应?

node.js - 为什么在使用 zip 或直接使用编辑器在 gcloud 中部署 nodejs 函数时遇到错误?

c++ - mongodb - 将字段附加到 BSONObj