猫鼬Model.create()未保存文档

时间:2018-08-17 02:28:24

标签: node.js mongoose

所以我正在使用以下控制台CRUD应用程序:Node,Mongo,Mongoose,commander.js和inquirer.js。

在app.js中,addItem()是一个返回Model.create({obj})的函数,根据Mongoose文档,该函数应返回一个promise。但是,当我尝试在下一个then()中记录响应时,没有任何输出。在使用其他模型之前,这可以很好地工作,但现在还不行。我感到create()无法正常工作(我知道那没有用,因为在数据库中未创建任何集合),但是我什至不知道如何记录错误。我已经坚持了一两天了,似乎没有其他人遇到过这个问题。或者至少我不知道如何正确地解决问题。

app.js

#!/usr/bin/env node
const mongoose = require('mongoose');
mongoose.Promise = Promise; 
const program = require('commander');
const { prompt } = require('inquirer');
const {addItem, getItem, removeItem, makeArray} = require('./logic.js');
const {itemTypeQuestion, papyriQuestions, lampQuestions} = require('./questions');

const typeQuestions = (type) => {
    if(type === 'papyrus') {
        return prompt(papyriQuestions).then(resp => {resp.item_type = type; return resp})
    } else if (type === 'lamp') {
        return prompt(lampQuestions).then(resp => {resp.item_type = type; return resp})
    }
}

program
    .command('addItem')
    .alias('a')
    .description('Add an item')
    .action( () => {
        prompt(itemTypeQuestion)
        .then(resp => typeQuestions(resp.item_type))
        .then(answers => makeArray(answers, "more_ids", "other_ids", ", ") )
        .then(resp => addItem(resp))
        .then(resp => console.info(resp))
        .then(mongoose.disconnect())
        .catch(e => {
            console.error(e);
            mongoose.disconnect();
        })
    } )

logic.js

const mongoose = require('mongoose');
mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost:27017/museum_catalog', { useNewUrlParser: true });
const {Papyrus, Lamp} = require('./schema.js');

/**
* @function  [addItem]
* @returns {Promise} Promise
*/
const addItem = (item) => {
    if (item.item_type === 'papyrus') {
        return Papyrus.create(item)
    } else if (item.item_type === 'lamp') {
        return Lamp.create(item)
    } 
}
const makeArray = (input, field, newKey, separator) => {
    input[newKey] = [];
    if (input[field] != 0) {
        input[field].split(separator).forEach(element => {
            input[newKey].push(element)
        });
    }
    return input;
}

module.exports = {addItem, getItem, removeItem, makeArray}

schema.js

const mongoose = require('mongoose');

// https://www.npmjs.com/package/mongoose-extend-schema
function extendSchema (Schema, definition, options) {
    return new mongoose.Schema(
      Object.assign({}, Schema.obj, definition),
      options
    );
  }


// Define Item schema
const itemSchema = mongoose.Schema({
    primary_id: {type: String, required: true, lowercase: true, unique: true, trim: true, index: true},
    other_ids: [],
    item_type: {type: String, required: true, lowercase: true, trim: true},
    description: {type: String, lowercase: true, trim: true},
    date_created: { type: Date, default: Date.now },
    hidden: {type: Boolean, default: false},
    height: Number,
    width: Number
})

// Papyrus schema & model
const papyrusSchema = extendSchema(itemSchema, {
    item_type: {type: String, default: 'papyrus', lowercase: true},
    language: {type: String, required: true, lowercase: true, trim: true},
});

const Papyrus = mongoose.model('papyrus', papyrusSchema);

// Lamp schema & model
const lampSchema = extendSchema(itemSchema, {
    item_type: {type: String, default: 'lamp', lowercase: true},
    isInscription: Boolean,
    language: {type: String, lowercase: true, trim: true},
})
const Lamp = mongoose.model('lamps', lampSchema);

module.exports = {Papyrus, Lamp};

也许我不正确地理解Promises或Mongoose的工作方式。此外,我们总是欢迎您提出关于其他事物的任何一般反馈

*编辑-固定8/18/18 在 schema.js 中,我添加了

const testItem = { primary_id: 'Je.41',
more_ids: 'C90',
description: 'test',
height: '12',
width: '12',
hidden: false,
language: 'test',
item_type: 'papyrus',
other_ids: [ 'C90' ] }
Papyrus.create(testItem).then(resp => {console.log(resp)}).catch(e => {console.error(e)})

让它在启动时创建项目并收到此错误:

MongoError: server instance pool was destroyed

显然,该应用断开连接的时间太早。在 app.js 中,我更改了.then(mongoose.disconnect())> .then(resp => mongoose.disconnect()),并成功了。

我仍然不确定

  1. 为什么错误从未记录?
  2. disconnect()进入then()以来,它是否应该等待?

仍然试图弄清楚这些承诺。

0 个答案:

没有答案