我尝试插入from nodejsto mangodb,我能够将文档插入数据库,但我不知道如何获取ID,我可以在插入成功时获取ID吗?这是insert.jsconst 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.jsconst 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
1 回答
Cats萌萌
TA贡献1805条经验 获得超9个赞
save 方法还在回调中提供响应。请检查以下代码:
newvideo.save((err, video) => {
if (err) {
res.status(500).json({
message: { msgBody: "Error has occured", msgError: true },
});
} else {
//get the id of inserted video
let videoId = video._id;
res.status(201).json({
message: { msgBody: "Add success", msgError: false },
});
}
});
添加回答
举报
0/150
提交
取消