我尝试使用Mongoose将对象保存到本地MongoDB数据库。以下代码将歌曲保存在播放列表中并对其进行计时:
console.time('saveSong');
playlistSong = await (new PlaylistSong({
added: new Date(),
url: song.url,
title: song.title,
thumbnail: song.thumbnail,
duration: song.duration
}).save());
console.timeEnd('saveSong');
此代码运行时,输出如下:
saveSong: 2021.505ms
但是,当我查看MongoDB服务器中的性能分析日志时,它表示插入执行时间为0ms。在这个简单的查询中花了那么多时间,我该如何改进呢?
该模型具有一个简单的模式,其中包含一些属性:
const playlistSongSchema = new mongoose.Schema({
added: Date,
addedBy: String,
removed: Date,
removedBy: String,
finished: Date,
likes: [String],
dislikes: [String],
url: String,
title: String,
thumbnail: String,
duration: Date
});
playlistSongSchema.index({ isRemoved: -1, isFinished: 1, added: 1 });
exports.PlaylistSong = mongoose.model('PlaylistSong', playlistSongSchema);
修改
不仅保存,而且查找查询也需要大约2秒才能执行。 E.g。
console.time('getSong');
let video = await YoutubeVideo.findOne({ videoId });
console.timeEnd('getSong');
输出:
getSong: 2027.283ms
编辑#2:
我可以将代码缩减为:
await mongoose.connect(`mongodb://localhost:27017`);
const testSchema = new mongoose.Schema({ testAttr: Boolean });
const TestObject = mongoose.model('TestObject', testSchema);
console.time('save');
await (new TestObject({ testAttr: true }).save());
console.timeEnd('save');
console.time('find');
await TestObject.findOne();
console.timeEnd('find');
这个输出是:
save: 15.009ms
find: 1015.816ms
但是,如果我将两个对象相互保存,则保存会变慢并且查找速度会加快。
console.time('save');
await (new TestObject({ testAttr: false }).save());
await (new TestObject({ testAttr: false }).save());
console.timeEnd('save');
console.time('find');
await TestObject.findOne({ testAttr: true });
console.timeEnd('find');
输出:
save: 1042.974ms
find: 30.846ms
使用mongodb
模块代替mongoose
会产生相同的结果。