【发布时间】: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
【问题讨论】: