javascript - MongoDB - Mongoose - TypeError:保存不是函数
问题描述
我试图通过首先使用 .findById 获取文档,然后使用新值更新该文档中的字段来对 MongoDB 文档(使用 mongoose)执行更新。我对此还是有点陌生,所以我使用了一个教程来弄清楚如何让它工作,然后我一直在更新我的代码以满足我的需要。这是教程:使用 Angular 4 的 MEAN App 教程。原始代码定义了一个模式,但我的要求是一个通用的 MongoDB 接口,它将简单地接收发送给它的任何有效负载并将其发送到 MongoDB。原来的教程是这样的:
exports.updateTodo = async function(todo){
var id = todo.id
try{
//Find the old Todo Object by the Id
var oldTodo = await ToDo.findById(id);
}catch(e){
throw Error("Error occured while Finding the Todo")
}
// If no old Todo Object exists return false
if(!oldTodo){
return false;
}
console.log(oldTodo)
//Edit the Todo Object
oldTodo.title = todo.title
oldTodo.description = todo.description
oldTodo.status = todo.status
console.log(oldTodo)
try{
var savedTodo = await oldTodo.save()
return savedTodo;
}catch(e){
throw Error("And Error occured while updating the Todo");
}
}
但是,由于我不想要一个模式并且想要允许任何东西通过,我不想将静态值分配给特定的字段名称,如标题、描述、状态等。所以,我想出了这个:
exports.updateData = async function(update){
var id = update.id
// Check the existence of the query parameters, If they don't exist then assign a default value
var dbName = update.dbName ? update.dbName : 'test'
var collection = update.collection ? update.collection : 'testing';
const Test = mongoose.model(dbName, TestSchema, collection);
try{
//Find the existing Test object by the Id
var existingData = await Test.findById(id);
}catch(e){
throw Error("Error occurred while finding the Test document - " + e)
}
// If no existing Test object exists return false
if(!existingData){
return false;
}
console.log("Existing document is " + existingData)
//Edit the Test object
existingData = JSON.parse(JSON.stringify(update))
//This was another way to overwrite existing field values, but
//performs a "shallow copy" so it's not desireable
//existingData = Object.assign({}, existingData, update)
//existingData.title = update.title
//existingData.description = update.description
//existingData.status = update.status
console.log("New data is " + existingData)
try{
var savedOutput = await existingData.save()
return savedOutput;
}catch(e){
throw Error("An error occurred while updating the Test document - " + e);
}
}
我最初的问题是我在获取新值来覆盖旧值时遇到了很多问题。现在已经解决了,我收到“TypeError:existingData.save 不是函数”的错误。我在想数据类型发生了变化或其他什么,现在它不被接受。当我取消注释旧教程代码中的静态值时,它可以工作。我在加入对象之前和之后的控制台日志记录进一步支持了这一点,因为第一个打印实际数据,第二个打印 [object Object]。但是,我似乎无法弄清楚它在期待什么。任何帮助将不胜感激。
编辑:我想通了。显然 Mongoose 有自己的“模型”数据类型,如果你使用 JSON.stringify 之类的东西对底层数据做任何疯狂的事情,它就会改变。我使用 Object.prototype.constructor 来确定实际的对象类型,如下所示:
console.log("THIS IS BEFORE: " + existingData.constructor);
existingData = JSON.parse(JSON.stringify(update));
console.log("THIS IS AFTER: " + existingData.constructor);
我得到了这个:
THIS IS BEFORE: function model(doc, fields, skipId) {
model.hooks.execPreSync('createModel', doc);
if (!(this instanceof model)) {
return new model(doc, fields, skipId);
}
Model.call(this, doc, fields, skipId);
}
THIS IS AFTER: function Object() { [native code] }
这向我展示了实际发生的情况。我添加了这个来修复它:
existingData = new Test(JSON.parse(JSON.stringify(update)));
在相关的说明中,此时我可能应该只使用本机 MongoDB 驱动程序,但它正在工作,所以我现在就把它放在我的待办事项列表中。
解决方案
您现在已经找到了解决方案,但我建议使用 MongoDB 驱动程序,这将使您的代码看起来与此类似,并使原始问题消失:
// MongoDB Settings
const MongoClient = require(`mongodb`).MongoClient;
const mongodb_uri = `mongodb+srv://${REPLACE_mongodb_username}:${REPLACE_mongodb_password}@url-here.gcp.mongodb.net/test`;
const db_name = `test`;
let db; // allows us to reuse the database connection once it is opened
// Open MongoDB Connection
const open_database_connection = async () => {
try {
client = await MongoClient.connect(mongodb_uri);
} catch (err) { throw new Error(err); }
db = client.db(db_name);
};
exports.updateData = async update => {
// open database connection if it isn't already open
try {
if (!db) await open_database_connection();
} catch (err) { throw new Error(err); }
// update document
let savedOutput;
try {
savedOutput = await db.collection(`testing`).updateOne( // .save() is being depreciated
{ // filter
_id: update.id // the '_id' might need to be 'id' depending on how you have set your collection up, usually it is '_id'
},
$set: { // I've assumed that you are overwriting the fields you are updating hence the '$set' operator
update // update here - this is assuming that the update object only contains fields that should be updated
}
// If you want to add a new document if the id isn't found add the below line
// ,{ upsert: true }
);
} catch (err) { throw new Error(`An error occurred while updating the Test document - ${err}`); }
if (savedOutput.matchedCount !== 1) return false; // if you add in '{ upsert: true }' above, then remove this line as it will create a new document
return savedOutput;
}
需要在此代码之前创建集合testing
,但这只是一次性的事情并且非常容易 - 如果您使用的是 MongoDB Atlas,那么您可以使用 MongoDB Compass / go in your online admin 来创建集合而无需一行代码...
据我所知,您应该需要复制该update
对象。以上将数据库调用从 2 减少到 1,并允许您重用数据库连接,可能在应用程序中有助于加快速度的其他任何地方。也不要将您的 MongoDB 凭据直接存储在代码中。
推荐阅读
- c# - 为什么当我使用它时,它会在我的库存中添加 2 个拾取?
- reactjs - 如何启用 onKeyDown?
- objective-c - 关于使用 AFNetworking 的 pod,我的项目中可以有两个相同框架的包吗?
- html - 无法在网站上移动背景图片
- video-streaming - 实时直播的最佳策略是什么
- jquery - 在智能向导中使用自定义验证?
- sass - 如何使用 Antd / Less 和 Sass / CSS 模块配置 Next.js
- c++ - 如何在 C++ 中将结构初始化为 0
- python - 在将权重归一化为 1 的数据框中插入新列时 Python 中的 SettingWithCopyWarning 错误
- vb.net - 下载,获取文件名并执行文件