我对 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;
Run Code Online (Sandbox Code Playgroud)
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');
})();
});
Run Code Online (Sandbox Code Playgroud)
这console.log向我显示了记录,但是当我这样做时,hostModel.save()我得到了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');
})();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11828 次 |
| 最近记录: |