为什么在使用Mongoose运行findOne时没有console.log?

时间:2017-04-06 08:47:00

标签: javascript node.js mongodb mongoose

我正在尝试用Mongoose查询我的MongoDB。

我在集合eclasses中的字段13中搜索字符串eClassSegment。控制台中打印了一些东西。为什么呢?

代码:

var mongoose        = require('mongoose'),
EClass              = require('./models/eclass');

mongoose.Promise    = require('bluebird');

EClass.findOne({ 'eClassSegment': '13' }, 'eClassSegment', function (err, result) {
    if (err) {
        console.log("Error: ", err);
    }
    console.log('All eClassSegments that equals 13: ', result);
});

Moongoose Schema:

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');

// Defining Mongoose Schema
const eClassSchema = mongoose.Schema({
    eclassSegment: { type: String, min: 2, max: 2 },
    eclassMainGroup: { type: String, min: 2, max: 2 },
    eclassGroup: { type: String, min: 2, max: 2 },
    eclassCommodityClass: { type: String, min: 2, max: 2 },
    preferredName: { type: String, max: 80 },
    definition: { type: String, max: 1023 },
    level: { type: String, min: 1, max: 1 },
    mkSubclass: { type: String, min: 1, max: 1 },
    mkKeyword: { type: String, min: 1, max: 1 }
});

// Create mongoose model
module.exports = mongoose.model('EClass', eClassSchema);

MongoDB中的文档示例(我有许多文档eClassSegment = '13' ..)

{
    "_id" : ObjectId("58e5d8d8fc0788063e587e1a"),
    "mkKeyword" : "0",
    "mkSubclass" : "1",
    "level" : "1",
    "definition" : "Services for the development of a product basically on the basis of service contracts or contract development",
    "preferredName" : "Development (Service)",
    "eclassCommodityClass" : "00",
    "eclassGroup" : "00",
    "eclassMainGroup" : "00",
    "eclassSegment" : "13",
    "__v" : 0
}

2 个答案:

答案 0 :(得分:1)

因此,您正在尝试搜索eClassSegment

但架构和数据库中的密钥是eclassSegment

答案 1 :(得分:0)

我忘了连接数据库......需要一些咖啡...: - )

这是解决方案!

var mongoose        = require('mongoose'),
    EClass          = require('./models/eclass');

mongoose.Promise    = require('bluebird');

mongoose.connect('mongodb://localhost/eclassCSV');

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
    var geteClass = function() {
        EClass.findOne({ 'eclassSegment': '13' }, 'eclassSegment', function (err, result) {
            if (err) {
                console.log('Error: ', err);
            }
            console.log('All eclassSegments that equals 13: ', result);
        })
        .then(function() {
            mongoose.disconnect();
        })
        .catch(function(err) {
            console.log('There was an error', err);
        });
    };
    geteClass();
});

结果的Console.log示例

All eclassSegments that equals 13:  { _id: 58e5d8d8fc0788063e587e1a, eclassSegment: '13' }