【问题标题】:I am not able to save the data to mongodb using node js我无法使用节点 js 将数据保存到 mongodb
【发布时间】:2018-06-02 07:17:49
【问题描述】:
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!');
    });

【问题讨论】:

  • 你能添加一些与你的错误相关的代码sn-p吗? IE。您的 john 对象所在的位置
  • 请不要发布代码图片,请按照帮助中心提供给您的说明在此处包含所有相关代码。
  • //这里是源代码
  • 我已经编辑了问题,请看一下

标签: node.js mongodb mongoose mongoose-schema


【解决方案1】:

您的代码:

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() 就可以了

【讨论】:

  • var Person = mongoose.model('Person', personSchema); var john = new Person({ firstname: 'John', lastname: 'Doe', address: '555 Main St.' }); john.save(function(err) { if (err) throw err; console.log('person saved!'); }); //但我仍然无法在控制台上收到消息
  • 消息没有打印在控制台上
猜你喜欢
  • 2016-02-13
  • 1970-01-01
  • 2020-06-22
  • 2020-11-04
  • 2019-01-26
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多