我对 Mongoose 和 MongoDB 本身相当陌生,我试图保存一堆通过 insertMany 方法插入的文档,但它没有保存文档。
这是我的代码:
Model:
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');
})();
});
That console.log
向我展示记录,但是当我这样做时hostModel.save()
I get hostModel.save is not a function
.
如何保存插入的文档?
非常感谢您的帮助!
无需创建实例new hostModel()
这里...直接使用hostModel
并且也没有必要save()
也因为插入许多本身创建了集合......并确保payload.data
有对象数组
router.post('/host', function (req, res, next) {
const array = [{hostname: 'hostname', timestamp: 'timestamp'},
{hostname: 'hostname', timestamp: 'timestamp'}]
var payload = req.body;
(async function(){
const insertMany = await hostModel.insertMany(array);
console.log(JSON.stringify(insertMany,'','\t'));
res.status(200).send('Ok');
})();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)