javascript - mongodb:将字段移动到新文档并更新字段和数组

标签 javascript mongodb meteor

Collection.find({ $and: [ {title: { $exists: true}}, {reference: { $exists: true }} ]}).pretty()

这给了我一些具有以下结构的文档:

{
    "_id" : "EJBFtZ7EeGbBPwJaw",
    "title" : "title",
    "reference" : "8uujF9pivpGA37oQc",
    "parent" : "v7DJzq859XX4kvKPi",
    "ancestors" : [
        "v7DJzq859XX4kvKPi"
    ]
}

现在我必须以这种方式转换所有文档:

  1. 将标题移至新文档并
  2. parent ID更新为新文档
  3. 将新的 id 推送到祖先(在第一个位置!)

结果应该是:

{
    "_id" : "gzRn4nDKfeewb8EYE",    // new document
    "title" : "title",              // moved title
    "parent" : "v7DJzq859XX4kvKPi",
    "ancestors" : [
        "v7DJzq859XX4kvKPi"
    ]
},
{
    "_id" : "EJBFtZ7EeGbBPwJaw",    // removed title
    "reference" : "8uujF9pivpGA37oQc",
    "parent" : "gzRn4nDKfeewb8EYE", // update parent id to new id
    "ancestors" : [
        "gzRn4nDKfeewb8EYE",        // add new id at first pos
        "v7DJzq859XX4kvKPi"
    ]
}

所以我的想法是这样的:

Collection.find({ $and: [ {title: { $exists: true}}, {reference: { $exists: true }} ]}).forEach(function(doc) {
    // get data from source
    var id     = doc.id;
    var title  = doc.title;
    var parent = doc.parent;

    // insert new document
    var newId = Collection.insert({
        title: title,
        parent: parent,
        ancestors: [parent]
    });

    // update source document
    if (newId) {
        Collection.update(
            { _id: id },
            { 
                $set:   { parent: newId },   // update parent id
                $push:  { ancestors: newId } // update ancestors array
                $unset: { title: '' }        // remove title
            }
        );      
    }

});
  1. 但是执行 $push 会附加 id,而不是前置它。
  2. 使用 if (newId) {} 是否正确,还是应该将此部分放在 insert 的回调函数中?

如果有任何可能的改进,请告诉我。

最佳答案

1) 尝试 $position 变量 https://docs.mongodb.org/master/reference/operator/update/position/#up._S_position

2) 就我个人而言,我会执行与 MongoDB 插入方法相同的操作,返回创建的新 _ID。

问候

关于javascript - mongodb:将字段移动到新文档并更新字段和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35081536/

相关文章:

javascript - Protractor.js 测试用例,用于 angular2 中的水平滚动和垂直滚动

javascript - Blackberry 的 Socket.IO 支持

javascript - 将值从一个函数移动到另一个函数

c# - 在 MongoDB C# 驱动程序 2.2.2 中找不到 FindOne 方法

macos - SQLite 打不开——Meteor create app

javascript - 如何在客户端的 Meteor 中捕获/处理 net::ERR_CONNECTION_REFUSED

android - $ANDROID_HOME 的 Meteor 添加平台错误

javascript - 两个全宽 div 之间的 slider

javascript - 如何判断值数组是否全部存在于 mongodb 集合中的数组中?

javascript - 自定义验证和格式化从数据集返回的响应 - 初学者