从我所见,它看起来像是Mongoose在添加它,但是当我检查服务器的后端时,什么都没有,没有错误显示,正好是我要求结果时显示的内容。
{ n: 1,
nModified: 0,
upserted: [ { index: 0, _id: 5e369aa7bcc3e15c0f1d030b } ],
opTime:
{ ts: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1580636839 },
t: 14 },
electionId: 7fffffff000000000000000e,
ok: 1,
'$clusterTime':
{ clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1580636839 },
signature: { hash: [Object], keyId: [Object] } },
operationTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1580636839 } }
这是代码
const userData = {"UUID": query.uuid, "ipaddress":ip, "station":req.params.stationname};
var update = {'$set':{
"endtime":Date.now()
}},
options = { upsert: true};
Listeners.updateOne(userData, update, options, function(error, result) {
console.log(result);
if (!error) {
// If the document doesn't exist
if (!result) {
// Create it
result = new Listeners(userData);
// Save the document
result.save(function(error) {
if (!error) {
// Do something with the document
} else {
throw error;
}
});
}
}
else{
console.log(error);
}
});
我也尝试了以下方法
const userData = {"UUID": query.uuid, "ipaddress":ip, "station":req.params.stationname};
result = new Listeners(userData);
// Save the document
result.save(function(error) {
if (!error) {
// Do something with the document
} else {
throw error;
}
});
我得到的答复是
{ _id: 5e369e790cd7d60a7eef12c4,
UUID: '14456',
ipaddress: '::ffff:101.118.4.209',
station: 'PERTHRadio',
starttime: 2020-02-02T10:03:37.839Z }
这是mongoose.model
const mongoose = require('mongoose');
// define the User model schema
const ListenerSchema = new mongoose.Schema({
UUID: {
type: String,
// index: { unique: true }
},
ipaddress: {
type: String,
// index: { unique: true }
},
station: {type:String},
starttime:{
type: Date,
},
endtime:{
type: Date,
}
}, { collection: 'listeners'});
/**
* The pre-save hook method.
*/
ListenerSchema.pre('save', function saveHook(next) {
if (!this.starttime) {
this.starttime = new Date();
}
// return this
console.log(this)
next();
})
module.exports = mongoose.model('listeners', ListenerSchema);