【问题标题】:mongoose .save() not going into .save() function猫鼬 .save() 不进入 .save() 函数
【发布时间】:2017-03-28 00:14:26
【问题描述】:

我遇到了 mongoose .save() 函数的问题。

索引.js

var mongoose = require('mongoose');
var companySchema = rootRequire('models/company');
mongoose.connect('mongodb://localhost:27017/test');


var company = new companySchema({activate: false, company_code: '123', name: 'A123' });
console.log(company);
company.save(function(err){
    if(err){
    console.log("now it can be associated with db",err);    
    }
    else{
        console.log("bingo");
    }
});

我的控制台日志输出是

{ 激活:false,_id:582997952a3134cc08672607,名称:'A123',
公司代码:'123' }

我没有收到任何日志

console.log("现在可以关联db",err);

console.log("bingo");

我的 company.js 看起来像

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var companySchema = new Schema({

    name: {
        type: String,
        required: true,
        sparse: true,
        unique: true
    },
    company_code: {
        type: String,
        required: true
    },
    activate: {
        type: Boolean,
        default: false
    },
    logo: {
        type: String
    }

}, {
    collection: 'company'
});


var Company = mongoose.model('company',companySchema)

module.exports = Company;

【问题讨论】:

  • rootRequire看起来像什么?
  • DeprecationWarning: Mongoose: mpromise(mongoose 的默认承诺库)已弃用,
  • @Qop var rootRequire = require('root-require'); npm 的包
  • 你试过用var companySchema = mongoose.model('company')代替var companySchema = rootRequire('models/company');吗?
  • @Qop 谢谢我为模式设计和 api 制作了通用文件,它发现工作正常。但这并没有解决我的问题。如何将其包含在另一个文件中?

标签: javascript node.js mongodb mongoose database


【解决方案1】:

使用单个文件解决了我的问题,但不是可行的选择。

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

//Company Schema
var companySchema = new Schema({

    name: {
        type: String,
        required: true,
        sparse: true,
        unique: true
    },
    company_code: {
        type: String,
        required: true
    },
    activate: {
        type: Boolean,
        default: false
    },
    logo: {
        type: String
    }

}, {
    collection: 'company'
});


var Company = mongoose.model('company',companySchema)
//console.log(Company);


mongoose.connect('mongodb://localhost:27017/test');
var company = new Company({activate: false, company_code: '123', name: 'OSPL3' });

console.log(company);
company.save(function(err){
    console.log('comses');
    if(err){
    console.log("now it can be associated with db",err);    
    }
    else{
        console.log("bingo");
    }
});

我的问题与 rootRequire 相关吗?

【讨论】:

    【解决方案2】:

    我尝试执行你的代码,我刚刚添加了一行 var rootRequire = require('root-require'); 进入 index.js,它对我来说很好。

    【讨论】:

      【解决方案3】:

      Mongoose 应该在架构设计之前包含。

      如果你看看我之前的答案和代码会更清楚

      【讨论】:

        猜你喜欢
        • 2021-07-14
        • 2021-02-10
        • 1970-01-01
        • 2016-06-14
        • 1970-01-01
        • 2016-01-23
        • 2016-11-06
        • 2019-03-23
        • 2017-05-08
        相关资源
        最近更新 更多