我无法使用节点js将数据保存到mongodb

时间:2017-12-19 19:33:09

标签: node.js mongodb mongoose mongoose-schema

john.save(function(err) {
     ^

TypeError: Cannot read property 'save' of undefined
    at Object.<anonymous> (C:\Users\shreeranga\Documents\mongoconnect\mongo1.js:18:6)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3[enter image description here][1]**
**here is my code **
        var MongoClient = require('mongodb').MongoClient, format = require('util').format;
    var mongoose = require('mongoose');
    mongoose.Promise = require('bluebird');
    var mongodb=require('mongodb');
    MongoClient.connect('mongodb://127.0.0.1:27017/mydatabase');
    var Schema = mongoose.Schema;
    var personSchema = new Schema({
        firstname: String,
        lastname: String,
        address: String
    });
    var Person = mongoose.model('Person', personSchema);
    var john = Person({
        firstname: 'John',
        lastname: 'Doe',
        address: '555 Main St.'
    });
    john.save(function(err) {
        if (err) throw err;
        console.log('person saved!');
    });

1 个答案:

答案 0 :(得分:0)

您的代码:

var Person = mongoose.model('Person', personSchema);
var john = Person({
    firstname: 'John',
    lastname: 'Doe',
    address: '555 Main St.'
});
john.save(function(err) {
    if (err) throw err;
    console.log('person saved!');
});

您需要使用new来实例化 mongoose 模型文档:

var john = new Person({})

然后您的john.save()将正常工作