Save()在MongoDB后端中无法按预期工作

时间:2019-03-18 19:06:28

标签: mongodb mongoose

我试图确定为什么即使我有一个可保存的文档,但当我运行save()时,该文档仍是我的MongoDB / Node后端中的undefined

我的update()函数看起来像这样(是的,我使用save()而不是findOneAndUpdate()是有原因的-它与pre和{{ 1}}挂钩触发器:

post

我的exports.update = async function(req, res) { let customerToUpdate; let request = new RequestHandler( req, res, { // Allowed Parameters id: { type: String } }, [ // Required Parameters "id" ] ); try { customerToUpdate = await Customer.findOne({ _id: request.parameters.id }).exec(); // Array to push props to const reqProps = []; for (const [key, val] of Object.entries(req)) { if (key in customerToUpdate) { // Get the current prop value in db const oldVal = customerToUpdate[key]; // Store the new prop value customerToUpdate[key] = val; reqProps.push({ [key]: { new: val, old: oldVal } }); } } // Need to compare 'old' vs 'new' because of '_id' in reqProps array for (let prop of reqProps) { if (prop.old !== prop.new) { customerToUpdate.prop = prop.new; } } console.log('customerToUpdate: ', customerToUpdate); // this logs the entire document, including the change I've made await customerToUpdate.save((err, doc) => { console.log("doc: ", doc); // But here it is undefined... if (doc) { console.log("Customer update saved successfully."); request.documentCount = 1; request.sendResponse(doc); } if (err) return request.sendError("Customer update failed.", err); }); } catch (err) { return request.sendError(err, "Customer update failed"); } }; 模型/方案看起来像这样(注意,我正在Customer钩中为next()调用pre

save()

因此,如您从上面的代码中看到的,奇怪的是我可以控制台出完整的文档对象(包括已进行的更改),但是随后,当我在此之后立即调用"use strict"; const mongoose = require("mongoose"); // Common types const trigger = require("./triggers/customer"); const gfs = mongoose.model("gfs", new mongoose.Schema({}, { strict: false }), "fs.files"); let CustomerSchema = { __v: { type: Number, select: false }, deleted: { type: Boolean, default: false }, createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now }, name: { first: { type: String, trim: true }, last: { type: String, trim: true } }, avatar: { type: mongoose.Schema.Types.Object, ref: "gfs" }, type: { type: String, trim: true }, tags: [ { type: mongoose.Schema.Types.ObjectId, ref: "Keyword" } ], }; let Schema = mongoose.Schema(CustomerSchema, { timestamps: true }) .pre("save", function(next) { const doc = this; trigger.preSave(doc); next(); }) .post("save", function(doc) { trigger.postSave(doc); }) .post("update", function(doc) { trigger.postSave(doc); }); module.exports = mongoose.model("Customer", Schema); 这就是save()。更令人困惑的是,我正在与其他模型/控制器进行同样的事情,并且没有任何问题。为什么这里是undefined?我对undefined的工作方式不了解吗?

为了澄清,我没有在此save()函数上遇到错误。由于某种原因,我只是没有可用的文档来保存-因为正如我所说的,它位于save()块中的undefined内。

0 个答案:

没有答案
相关问题