簡體   English   中英

從Mongoose / MongoDB中的數組中刪除帶有ObjectId的對象

[英]Removing object with ObjectId from array in Mongoose/MongoDB

如何進入_carts數組並刪除_id為'1'的對象? 另外,我是否對ObjectId使用update和$ pull? 假設用戶_id和cart _id都是ObjectId。

user_id和cart_id也會返回一串ID(正在運行)。 我該怎么做呢?? 這只是我遇到的問題。

路由器文件

const User = require('../models/User');
const jwt = require('jwt-simple');
const config = require('../config/dev');
const mongoose = require('mongoose');
const ObjectId = mongoose.Types.ObjectId;

exports.deletelocalcartproduct = function (req, res, next) {
    const token = req.query.token;
    const secret = config.secret;
    const decoded = jwt.decode(token, secret);

    const user_id = decoded.sub; // THIS IS A STRING

    const cart_id = req.query.cart; // THIS IS A STRING

    // THE PROBLEM IS HERE
    const user = User.update(
        {'_id': ObjectId(user_id)},
        { $pull: { '_carts': { _id: (cart_id) }}},
        false,
        true
    );
    user.save();
}

用戶模型

const userSchema = new Schema({
    _carts: [{
        type: Schema.Types.ObjectId,
        ref: 'cart'
    }],
    admin: Boolean
});

推車型號

const cartSchema = new Schema({
    _product: {
        type: Schema.Types.ObjectId,
        ref: 'product'
    },
    quantity: Number
});

種子數據示例

const User1 = {
     _id: '1234',
     _carts: [{
              _id: '1',
              _product: {},
              quantity: 2
              }, 
              {
              _id: '2',
              _product: {},
              quantity: 4
              }],
        admin: false
    }

使用你們給我的答案中的更正,我在終端上收到此錯誤:

 (node:3042) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
[0] Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
[0] (node:3042) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
[0] TypeError: Cannot read property 'save' of undefined
[0]     at exports.deletelocalcartproduct (/Users/user/Desktop/bootiq/server/controllers/auth.js:76:10)
[0]     at Layer.handle [as handle_request] (/Users/user/Desktop/bootiq/server/node_modules/express/lib/router/layer.js:95:5)
[0]     at next (/Users/user/Desktop/bootiq/server/node_modules/express/lib/router/route.js:137:13)
[0]     at Route.dispatch (/Users/user/Desktop/bootiq/server/node_modules/express/lib/router/route.js:112:3)
[0]     at Layer.handle [as handle_request] (/Users/user/Desktop/bootiq/server/node_modules/express/lib/router/layer.js:95:5)
[0]     at /Users/user/Desktop/bootiq/server/node_modules/express/lib/router/index.js:281:22
[0]     at Function.process_params (/Users/user/Desktop/bootiq/server/node_modules/express/lib/router/index.js:335:12)
[0]     at next (/Users/user/Desktop/bootiq/server/node_modules/express/lib/router/index.js:275:10)
[0]     at jsonParser (/Users/user/Desktop/bootiq/server/node_modules/body-parser/lib/types/json.js:118:7)
[0]     at Layer.handle [as handle_request] (/Users/user/Desktop/bootiq/server/node_modules/express/lib/router/layer.js:95:5)
[0]     at trim_prefix (/Users/user/Desktop/bootiq/server/node_modules/express/lib/router/index.js:317:13)
[0]     at /Users/user/Desktop/bootiq/server/node_modules/express/lib/router/index.js:284:7
[0]     at Function.process_params (/Users/user/Desktop/bootiq/server/node_modules/express/lib/router/index.js:335:12)
[0]     at next (/Users/user/Desktop/bootiq/server/node_modules/express/lib/router/index.js:275:10)
[0]     at cors (/Users/user/Desktop/bootiq/server/node_modules/cors/lib/index.js:188:7)
[0]     at /Users/user/Desktop/bootiq/server/node_modules/cors/lib/index.js:224:17
[0] events.js:136
[0]       throw er; // Unhandled 'error' event
[0]       ^
[0] 
[0] TypeError: callback.apply is not a function
[0]     at /Users/user/Desktop/bootiq/server/node_modules/mongoose/lib/model.js:4074:16
[0]     at callback (/Users/user/Desktop/bootiq/server/node_modules/mongoose/lib/query.js:2981:9)
[0]     at /Users/user/Desktop/bootiq/server/node_modules/kareem/index.js:213:48
[0]     at /Users/user/Desktop/bootiq/server/node_modules/kareem/index.js:131:16
[0]     at _combinedTickCallback (internal/process/next_tick.js:131:7)
[0]     at process._tickCallback (internal/process/next_tick.js:180:9)

如果我找到用戶和控制台日志:

{ _id: 5a9d055cc4587fb6cb36ea99,
[0]   admin: false,
[0]   __v: 4,
[0]   _carts: 
[0]    [ { _id: 5a9d07208537e2b74cbf0c6c,
[0]        _product: [Object],
[0]        quantity: 3,
[0]        __v: 0 },
[0]      { _id: 5a9d120e2398caba6390321e,
[0]        _product: [Object],
[0]        quantity: 2,
[0]        __v: 0 },
[0]      { _id: 5a9d18293df497bcbb580a76,
[0]        _product: [Object],
[0]        quantity: 7,
[0]        __v: 0 } ]}

您的問題在更新功能中

User.update(
        {'_id':user_id}, // you not need to use ObjectId here
        { $pull: { '_carts': { _id: cart_id }}},
        function(err,result){
    // can you give here the output of console.log(result);
   }
    )
    User.save();

仔細查看您的問題后,我發現您的User模型架構有問題。 因此,我相應地更新了答案。

User模型中, _carts具有以下已使用的架構。

_carts: [{
        type: Schema.Types.ObjectId,
        ref: 'cart'
    }]

因此,根據您的架構,數組包含引用cart模型的Objectids (example: _carts:[ObjectId1,ObjectId2,Object3 ....])

但是在您的種子數據中,文檔是

const User1 = {
     _id: '1234',
     _carts: [{
              _id: '1',
              _product: {},
              quantity: 2
              }, 
              {
              _id: '2',
              _product: {},
              quantity: 4
              }],
        admin: false
    }

_carts數組中有objects 按照架構,它應該是ObjectIds而不是Objects

現在,根據您的查詢{ $pull: { '_carts': { _id: (cart_id) }}}您正在嘗試提取_id = cart_id的文檔。 但是,您的_carts架構中沒有_id可用。

所以這是我的分析。 如果要將cart詳細信息存儲在cart carts數組中。 然后,您的User模型的架構應為

_carts : [cartSchema]

否則,您的update查詢將沒有問題。 它應該工作。

您提到的錯誤是由於mongodb連接問題所致。 請遵循更新的Mongoose文檔,了解如何正確連接Mongodb。

暫無
暫無

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

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