Mongo Shell .save()触发成功回调,但文档不在数据库中

时间:2018-10-19 20:14:17

标签: mongodb mongoose

我正在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

1 个答案:

答案 0 :(得分:1)

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

use uberEstimator
db.estimates.count()