我尝试插入from nodejsto mangodb,我能够将文档插入数据库,但我不知道如何获取ID,我可以在插入成功时获取ID吗?
这是insert.js
const Video = require("../models/Video");
Video.findOne({ title }, (err, user) => {
if (err) {
res
.status(500)
.json({ message: { msgBody: "Error hac occured", msgError: true } });
}
if (user) {
res.status(400).json({
message: { msgBody: "Title is already taken", msgError: true },
});
} else {
const newvideo = new Video({ title, singer, country, genre });
newvideo.save((err) => {
if (err) {
res.status(500).json({
message: { msgBody: "Error has occured", msgError: true },
});
} else {
res.status(201).json({
message: { msgBody: "Add success", msgError: false },
});
}
});
}
});
这是Video.js
const mongoose = require("mongoose");
const VideoSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
singer: {
type: String,
},
country: {
type: String,
required: true,
},
genre: {
type: String,
required: true,
},
});
module.exports = mongoose.model("video", VideoSchema);
希望你们明白我在问什么:D
Cats萌萌
相关分类