我正在尝试在集合中创建文档,但是许多插入似乎无法正常工作。它不会抛出任何错误或其他任何东西,但是数据库中的结果集合为空。
./connect.js
const mongoose = require('mongoose');
const uri =
'mongodb://localhost:27017/devices?poolSize=20&w=majority&replicaSet=rs0';
mongoose.connect(uri, {
useUnifiedTopology: true,
useNewUrlParser: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'Connection error:'));
db.once('open', () => {
console.log('connected');
});
./model/device.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const DeviceSchema = new Schema(
{
name: { type: String, required: true },
serial_number: { type: Number, unique: true, required: true },
capability: { type: String, required: true },
created_at: { type: Date, required: true },
updated_at: { type: Date, required: true },
},
{
collection: 'device',
strict: 'throw',
}
);
module.exports = mongoose.model('Device', DeviceSchema);
./populateDevice.js
const Device = require('../model/device');
const config = require('../config');
const {
serialNumberByDeviceType: {
temperature: temperatureSerialNumnber,
humidity: humiditySerialNumnber,
},
} = config;
Device.insertMany([
{
name: 'Temperature Device',
serial_number: temperatureSerialNumnber,
capability: 'temperature',
created_at: 1602764995055,
updated_at: 1602764995055,
},
{
name: 'Humidity Device',
serial_number: humiditySerialNumnber,
capability: 'humidity',
created_at: 1602765017160,
updated_at: 1602765017752,
},
])
.then(() => console.log('Data inserted.'))
.catch((error) => console.log(error));
首先我运行node connect.js
输出中的输出是:
connected
然后我运行node populateDevice.js
然后在执行脚本后清除控制台。数据库的实际集合不包含任何文档。
能帮我吗?谢谢。