我有一个对象数组。如果它们满足某个条件,我会向对象添加另一个属性并将其保存到我的数据库(Mongo)。但是,附加属性永远不会出现在数据库中。我在保存之前已经将它记录到控制台以确认它在那里,但是当我检查mongo shell时它永远不会出现。
function nearbyPlaces(distance, unit) {
db.Places.find({}, function (err, places) {
var distance = Number(distance) || 1000
var unit = unit || 'km'
for(var i = 0; i < places.length; i++) {
var nearby = []
var start = {}
if(places[i].latitude && places[i].longitude){
start.latitude = places[i].latitude
start.longitude = places[i].longitude
}
for(var j = 0; j < places.length; j++){
var end = {}
if(i !== j && places[j].latitude && places[j].longitude) {
end.latitude = places[j].latitude
end.longitude = places[j].longitude
var dist = haversine(start, end, {unit: unit})
if(dist <= distance) {
if(places[j]) {
var temp = places[j]
temp.distance = dist
nearby.push(temp)
}
}
}
}
//console.log('distance is',nearby[0].distance)
// this prints out correctly
var record = {
origin: places[i].origin,
latitude: places[i].latitude,
longitude: places[i].longitude,
nearby: nearby,
max_distance: distance,
unit: unit
}
console.log('saving record')
var thingy = new db.Nearby(record)
thingy.save(function (err) {
if(err) {
console.log(err)
}
if(!err) {
console.log('saved')
}
})
}
})
}
// This line comes from index.js
exports.Nearby = Mongoose.model('Nearby', require('./nearby'))
// The Nearby schema
var mongoose = require('mongoose')
var db = require('./index')
var trimmedString = {type: String, trim: true}
var NearbyPlaces = new mongoose.Schema({
origin: String,
latitude: Number, // latitude in degrees
longitude: Number,
nearby: Array,
max_distance: Number,
unit: String
})
NearbyPlaces.index({origin: 1})
NearbyPlaces.index({distance: 1})
NearbyPlaces.index({unit: 1})
module.exports = NearbyPlaces
附近[x] .distance永远不会出现。有谁知道这是为什么?
答案 0 :(得分:0)
尝试如下所示,
var temp = places[j].toObject()
temp.distance = dist
nearby.push(temp)