从Mongoose / MongoDB中的数组中删除ObjectId对象

时间:2018-03-06 05:34:44

标签: javascript node.js mongodb mongoose

如何进入_carts数组并删除_id为'1'的对象?另外,我使用更新和$ pull右边的ObjectId?假设用户_id和cart _id都是ObjectIds。

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 } ]}

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

仔细查看您的问题后,我发现您的User模式架构出了问题。所以我相应地更新了答案。

User模型中,_carts字段具有您使用的以下架构。

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

因此,根据您的架构,数组包含Objectids,其中引用了cart模型。 (example: _carts:[ObjectId1,ObjectId2,Object3 ....])

但是在种子数据中,文档是

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

objects数组中有_carts。根据架构,它应该是ObjectIds而不是Objects

现在根据您的查询{ $pull: { '_carts': { _id: (cart_id) }}},您正在尝试提取_id = cart_id的文档。但是_id架构中没有_carts可用。

所以这是我的分析。如果您想在cart数组中存储carts个详细信息。那么您的User模型的架构应该是

_carts : [cartSchema]

否则您的update查询没有问题。它应该工作。

您提到的错误是由mongodb连接问题引起的。请关注如何正确连接Mongodb的更新Mongoose文档。