簡體   English   中英

使用 Mongoose 更新許多時未定義

[英]Getting undefined when updating many using Mongoose

我有一個 Node.js 應用程序,它使用 Mongoose.js 與 MongoDB 交互。 我正在嘗試使用它,以便在發生某個操作(更新計划)時,它會使用某個 companyID(即屬於該公司的所有用戶)更新所有用戶。 下面我的代碼返回 undefined 找到了多少以及更新了多少。

const updated = User.updateMany({ companyID: req.body.companyID }, { 'company.stripe.plan': req.body.plan });
console.log(updated.n)
console.log(updated.nModified)

請求體

{ company:
   { stripe:
      { plan: '<>',
        subscriptionId: '<>',
        customerId: '<>',
        last4: '<>' },
     companyName: '<>'},
  isVerified: true,
  _id: '<>',
  email: '<>',
  companyID: 'fc5a653c-2f68-4925-9ff2-93fde2157453',
  updatedAt: '2020-02-10T01:32:53.510Z',
  createdAt: '2020-02-04T00:44:27.971Z',
  __v: 0,
  lastLogin: '2020-02-10T00:46:16.118Z',
  plan: '<>',
  subscriptionId: '<>' }

我編輯了一些不需要且可能不應該共享的信息。 req.body 的第一部分實際上是發送到 API 的單個用戶以及底部看到的計划和訂閱 ID。

我在第一個代碼段中看到的 console.log 返回 undefined 當我希望它返回 2 個找到的記錄和 2 個更新/修改的記錄時。

編輯** 看到這里不清楚是我縮小的用戶模型

var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var timestamps = require('mongoose-timestamp');
var bcrypt = require('bcrypt-nodejs');

var UserSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: String,
    companyID: {
        type: String,
        required: true
    },


    company: {
        stripe: {
            customerId: String,
            subscriptionId: String,
            last4: String,
            plan: {
                type: String,
                default: 'default'
            },
        }
    },
    lastLogin: Date,
    lastChangedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
});

除了需要的功能之外的所有功能都已刪除

exports.plan = function(req, res, next) {
...
    console.log(req.body)
    console.log(req.body.companyID)
    const updated = User.updateMany({ companyID: req.body.companyID }, { 'company.stripe.plan': req.body.plan });
    console.log(updated.n)
    console.log(updated.nModified)
    return res.json({success: true})
....
}

已解決,問題是更新的鍵/值中的鍵,它不適用於點表示法,但是當我切換到括號表示法時,它現在正在工作。 我認為這可能是 mongoose 的一個限制,因為我覺得我以前遇到過這個錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM