从 Mongoose/MongoDB 中的数组中删除带有 ObjectId 的对象 [英] Removing object with ObjectId from array in Mongoose/MongoDB

查看:82
本文介绍了从 Mongoose/MongoDB 中的数组中删除带有 ObjectId 的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何进入 _carts 数组并删除 _id 为1"的对象??另外,我是否将更新和 $pull 与 ObjectId 一起使用?假设用户_id 和cart _id 都是ObjectId.

How do I go into the _carts array and delete the object with _id of '1'?? Also, am I using the update and $pull right with the ObjectId?? Assuming that the user _id and cart _id are both ObjectIds.

还有 user_id 和 cart_id 返回一个 id 字符串(并且正在工作).我该怎么做呢??这只是我遇到问题的查询.

Also user_id and cart_id gives a string of the ids back (and are working). How do I do this?? It's just the query that I'm having trouble with.

路由器文件

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
    }

使用了你们给我的答案中的更正,我的终端出现了这个错误:

Used the corrections from the answers you guys gave me, and I got this error on my terminal:

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

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

If I find the user and console log:

{ _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 模型架构有问题.所以我相应地更新了答案.

After closely looking at your problem what I found is something wrong with your User Model schema. So I have updated the answer accordingly.

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

In your User model the _carts filed has following schema you have used.

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

因此,根据您的架构,该数组包含 Objectids,它引用了 cart 模型.(例如:_carts:[ObjectId1,ObjectId2,Object3 ....])

So as per your schema the array contains Objectids which has reference to cart model. (example: _carts:[ObjectId1,ObjectId2,Object3 ....])

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

But in your Seed data the document is

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

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

which has objects in _carts array. As per schema it should be ObjectIds not Objects

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

Now as per your query { $pull: { '_carts': { _id: (cart_id) }}} you are trying to pull the document which has _id = cart_id. But there is no _id available in your _carts schema .

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

So here is my analysis. If you want store cart details in carts array. Then your User model's schema should be

_carts : [cartSchema]

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

Otherwise your update query has no problem. It should work.

您提到的错误是由于 mongodb 连接问题造成的.请按照更新的 Mongoose 文档了解如何正确连接 Mongodb.

The error you have mentioned is due to mongodb connection issue. Please follow updated Mongoose doc on how to connect Mongodb properly.

这篇关于从 Mongoose/MongoDB 中的数组中删除带有 ObjectId 的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆