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



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

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

use uberEstimator
db.estimates.count()

最新更新