为什么它没有控制台.log运行 findOne 与猫鼬



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

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

法典:

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);
});

蒙古斯模式:

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
}

所以你正在尝试搜索eClassSegment .

但架构和数据库中的键是eclassSegment

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

这是解决方案!

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();
});

控制台示例.log结果

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

最新更新