【问题标题】:Mongo shell .save() triggers success callback but document not in databaseMongo shell .save() 触发成功回调,但文档不在数据库中
【发布时间】:2018-10-20 04:17:46
【问题描述】:

我在 Mongo 文档上调用 .save() 方法。成功回调被触发,我通过了保存的文档,但我的数据库中的表中仍然有零个文档。 db.estimates.count() 当我使用 uberEstimator 数据库时返回 0。

我已经根据我拥有的其他工作代码对该代码进行了密切建模,但我就是不知道我哪里出错了。我没有正确使用.save()?

const mongoose = require('mongoose');
if (process.env.MONGODB_URI) {
  mongoose.connect(process.env.MONGODB_URI);
} else {
  mongoose.connect('mongodb://localhost/uberEstimator')
}

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => console.log('mongoose connection open!'));

var estimateSchema = new mongoose.Schema({
  rideTier: String,
   ...
});

var Estimate = mongoose.model('Estimate', estimateSchema);

const save = ({display_name, distance, high_estimate, low_estimate, duration, estimate, currency_code, 
start_latitude, start_longitude, end_latitude, end_longitude, start_address, end_address}) => {
  let props = {
    rideTier: display_name,
    ...
  }
  var estimate = new Estimate(props);
  console.log(estimate);
  estimate.save((err, newEstimate) => {
    if (err) console.log(err);
    console.log('saved new estimate to db');
    console.log(newEstimate);
  })
};

var sample = JSON.parse('{"localized_display_name": "uberX","distance": 6.17,"display_name": "uberX","product_id": "a1111c8c-c720-46c3-8534-2fcdd730040d","high_estimate": 17,"low_estimate": 13,"duration": 1080,"estimate": "$13-17","currency_code": "USD"}')
sample.start_address = '300 Albany St';
save(sample);

我得到了这些日志:

mongoose connection open!
saved new estimate to db
{ _id: 5bca37267a478b31718445f3,
  rideTier: 'uberX',
  distance: 6.17,
  highEstimate: 17,
  lowEstimate: 13,
  duration: 1080,
  estimateString: '$13-17',
  currency: 'USD',
  start_address: '300 Albany St',
  __v: 0 }

但是通过 Mongo shell 检查表格时仍然得到以下信息:

> use uberEstimator
switched to db uberEstimator
> show tables
estimates
> use estimates
switched to db estimates
> db.estimates.count()
0

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    命令use estimates 将当前数据库切换到estimates,我想这不是你想要在这里实现的。根据您的代码,您似乎想浏览 uberEstimator database 和 estimates collection,因此您可以简单地尝试:

    use uberEstimator
    db.estimates.count()
    

    【讨论】:

    • 就是这样。谢谢!
    猜你喜欢
    • 2014-02-22
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    相关资源
    最近更新 更多