简体   繁体   English

在MongoDB中可以直接引用ObjectID,但在Mongoose中则不能

[英]Referring to ObjectIDs directly in MongoDB works, but not in Mongoose

The first code snippet achieves the desired effect: 第一个代码段达到了预期的效果:

//in mongodb console:
db.collection.update({"username":"name"}, {$pull : { "task" : { "_id" : ObjectId("55280205702c316b6d79c89c")}}})

Yet this second (seemingly equivalent) code snippet written in Mongoose does not: 但是,用猫鼬编写的第二个(看似等效)代码片段没有:

//in Mongoose:
var taskID = "55280205702c316b6d79c88c"
var pull = { $pull : {}};
var idObj = {};
idObj["_id"] = taskID;
pull.$pull["task"] = idObj;

collectionModel.update({"username": "name"}, pull) //fails to work since taskID just shows up as a literal string 55280205702c316b6d79c88c instead of ObjectId("55280205702c316b6d79c88c")

Other things I've tried: 我尝试过的其他方法:

  • making var taskID equal to the string 'ObjectId(\\"55280205702c316b6d79c88c\\")' 使var taskID等于字符串'ObjectId(\\"55280205702c316b6d79c88c\\")'
  • setting var taskID equal to mongoose.Types.ObjectId("55280205702c316b6d79c88c") 设置var taskID等于mongoose.Types.ObjectId("55280205702c316b6d79c88c")

How can I achieve the effect in the former code snippet in Mongoose? 如何在Mongoose的以前的代码片段中实现效果?

Import ObjectId type and use it in your query : 导入ObjectId类型并在查询中使用它:

var ObjectId = require('mongoose').Types.ObjectId; 
idObj["_id"] = new ObjectId("55280205702c316b6d79c88c");

After you did the $pull operation in mongodb shell and tried the same update operation in Mongoose with the same ObjectId, it didn't work because the task array object element with "_id": ObjectId("55280205702c316b6d79c88c") was removed by the previous mongodb shell operation. 在mongodb shell中执行$pull操作并在具有相同ObjectId的Mongoose中尝试了相同的更新操作后,此操作不起作用,因为带有"_id": ObjectId("55280205702c316b6d79c88c")的任务数组对象元素"_id": ObjectId("55280205702c316b6d79c88c")已由先前的操作删除。 mongodb shell操作。

Try first running the same query from Mongoose but with a different and existing taskID which is cast to ObjectId. 尝试首先从Mongoose运行相同的查询,但是使用已转换为ObjectId的现有任务ID并有所不同。 You could add an extension to the String object as follows: 您可以将扩展名添加到String对象,如下所示:

String.prototype.toObjectId = function() {
    var ObjectId = (require("mongoose").Types.ObjectId);
    return new ObjectId(this.toString());
};

var taskID = "55280205702c316b6d79c88d".toObjectId(); // a different _id
collectionModel.update( 
    { "username": "name" }, 
    { "$pull" : { "task": { "_id": taskID } } }, 
    function (err, result) {
        console.log(result);        
    }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM