我对Mongoose和MongoDB本身很新,我试图保存一堆通过insertMany方法插入的文件,但它没有保存文档。
这是我的代码:
型号:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var hostSchema = new Schema({
hostname: String,
timestamp: Number,
});
var hostModel = mongoose.model('host', hostSchema, 'host');
module.exports = hostModel;
ExpressJS邮政路线
var mongoose = require('mongoose');
var hostModel = require('../../models/Host');
router.post('/host', function (req, res, next) {
var payload = req.body;
(async function(){
var host = new hostModel();
const insertMany = await hostModel.insertMany(payload.data);
console.log(JSON.stringify(insertMany,'','\t'));
const saveMany = await hostModel.save();
res.status(200).send('Ok');
})();
});
console.log
向我显示了记录,但当我hostModel.save()
时,我得到了hostModel.save is not a function
。
如何保存插入的文档?
非常感谢您的帮助!
答案 0 :(得分:1)
无需在此处创建实例new hostModel()
...直接使用hostModel
也不需要save()
因为插入多个本身会创建集合...并确保{ {1}}包含对象数组
payload.data
答案 1 :(得分:0)
对于那些面临相同问题的人。我已将updateMany
与criteria
结合使用,如下所示:
router.post('/heatmap', function (req, res, next) {
let payload = req.body;
(async function(){
let heatmapDate = new Date(payload[0].heatmapdata[0].timestamp).toISOString().substring(0, 10);
payload[0].heatmapDate = heatmapDate;
let sessionData = payload[0];
sessionData.sessionrecordheatmap = payload[0].heatmapdata;
let criteriaSession = {
sessionId:{ $eq: payload[0].sessionId}
};
const updatetManySession = await updateManySessionRecord(sessionrecordModel, criteriaSession, sessionData);
res.status(200).send(updatetManyHeatmap);
})();
});
async function updateManySessionRecord(schema, criteria, data){
return new Promise((resolve, reject) => {
schema.updateMany(criteria,
{
id: data.id,
clientIp: data.clientIp,
device: data.device,
heatmapDate: data.heatmapDate,
protocol: data.protocol,
hostname: data.hostname,
pagePath: data.pagePath,
pageImage: data.pageImage,
pageTitle: data.pageTitle,
clientHeight: data.clientHeight,
clientWidth: data.clientWidth,
$push: {
sessionrecordheatmap: data.sessionrecordheatmap,
}
},
{
multi: true,
upsert: true
},
function(err, res) {
if (err) {
console.log('ERROR - UPDATE MANY SESSIONRECORD: ' + err);
reject('insertFirst');
}
else{
resolve('ok')
}
});
});
}