【问题标题】:Removing object with ObjectId from array in Mongoose/MongoDB从 Mongoose/MongoDB 中的数组中删除带有 ObjectId 的对象
【发布时间】:2018-08-13 21:47:59
【问题描述】:

如何进入 _carts 数组并删除 _id 为 '1' 的对象?另外,我是否将更新和 $pull 与 ObjectId 一起使用?假设用户 _id 和购物车 _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 } ]}

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您的问题在更新功能中

    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();
    

    【讨论】:

    • 你能给出console.log(result)的输出吗?
    • 我在终端上遇到的错误在帖子上(刚刚更新),在我的控制台日志上
    • createError.js:16 Uncaught (in promise) 错误:在 XMLHttpRequest.handleLoad (xhr) 解决 (settle.js:18) 时的 createError (createError.js:16) 请求失败,状态码为 500 .js:77)
    【解决方案2】:

    仔细查看您的问题后,我发现您的 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
        }
    

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

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

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

    _carts : [cartSchema]

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

    您提到的错误是由于mongodb 连接问题。请关注更新的Mongoose doc,了解如何正确连接 Mongodb。

    【讨论】:

    • 错误是关于 MongoDB 连接的。它的说法.open 已被弃用,而是使用openUri(),或者如果使用connect()createConnection(),则设置useMongoClient 选项。我不确定你是如何从 Mongoose 连接到的。
    • 我已经更新了答案看看,如果它对你有帮助,请告诉我@Ckusuma
    猜你喜欢
    • 2021-04-01
    • 2016-03-16
    • 2021-05-27
    • 2016-10-04
    • 2021-07-27
    • 1970-01-01
    • 2013-03-16
    相关资源
    最近更新 更多