mongoose .save()不会进入.save()函数

时间:2016-11-14 11:11:33

标签: javascript node.js mongodb mongoose database

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

Index.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");
    }
});

我的控制台日志输出是

  

{activate:false,_id:582997952a3134cc08672607,姓名:' A123',
  company_code:' 123' }

我没有收到任何日志

  

console.log("现在它可以与db",错误相关联);

  

的console.log("宾果&#34);

我的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;

3 个答案:

答案 0 :(得分:0)

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

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相关的问题?

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

如果您查看我以前的答案和代码,将会更清楚