gpt4 book ai didi

javascript - 使用回调函数获取插入的文档_id

转载 作者:行者123 更新时间:2023-12-01 00:54:16 26 4
gpt4 key购买 nike

我正在尝试使用nodejs中的callback函数从MongoDB获取插入的文档_id(expressJS),但我收到此错误:

AssignmentDB.save is not a function

这是我的代码。有人可以帮助我如何通过 MongoDB

的回调函数获取 _id
router.route("/assignment/add").post((req, res) => {
let assignmentDb = new AssignmentDB(req.body);

AssignmentDB
.save(assignmentDb, function(err, records){
if(err) throw err;
res.status(200).send(records[0]._id); //should send the inserted documents _id
});

});

这是我的 AssignmentDB 模型,如下所示:

const mongoose= require('mongoose');
const Schema = mongoose.Schema;

let AssignmentDB = new Schema({
assignmentName: String,
assignmentDescription: String,
courseName: String,
assignmentDueDate: Date,
isNewAssignment: Boolean
});

module.exports = mongoose.model('AssignmentDB', AssignmentDB, 'AssignmentDB');

最佳答案

像这样更改你的路由器代码

router.route("/assignment/add").post((req, res) => {
let assignmentDb = new AssignmentDB(req.body);
assignmentDb.save(function(err, record){
if(err) throw err;
res.status(200).send(record._id); //should send the inserted documents _id
});

});

Save 方法将以对象而不是对象数组的形式返回保存的记录。另外,在模型实例上调用 save 方法。

下面是在 MongoDB 中保存记录的示例

var mongoose = require('mongoose');

// make a connection
mongoose.connect('mongodb://localhost:27017/tutorialkart');

// get reference to database
var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
console.log("Connection Successful!");

// define Schema
var BookSchema = mongoose.Schema({
name: String,
price: Number,
quantity: Number
});

// compile schema to model
var Book = mongoose.model('Book', BookSchema, 'bookstore');

// a document instance
var book = new Book({ name: 'Introduction to Mongoose', price: 10, quantity: 25 });

// save model to database
book.save(function (err, book) {
if (err) return console.error(err);
console.log(book + " saved to bookstore.");
});

});

关于javascript - 使用回调函数获取插入的文档_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56718145/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com