node.js 通过 mongoose 将项目推入 mongo 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33049707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:22:07  来源:igfitidea点击:

Push items into mongo array via mongoose

node.jsmongodbexpressmongoose

提问by Neurax

I've scoured SO a good bit looking for the answer but I'm sure that I'm lost for the right words to describe what I'm after.

我已经搜索了很多寻找答案,但我确信我迷失了正确的词来描述我所追求的东西。

Basically I have a mongodb collection called 'people' The schema for that collection is as follows:

基本上我有一个名为“people”的 mongodb 集合,该集合的架构如下:

people: {
         name: String, 
         friends: [{firstName: String, lastName: String}]
        }

Now, I have a very basic express application that connects to the database and successfully creates 'people' with an empty friends array.

现在,我有一个非常基本的 express 应用程序,它连接到数据库并成功地创建了一个带有空朋友数组的“人”。

In a secondary place in the application, a form is in place to add friends. The form takes in firstName and lastName and then POSTs with the name field also for reference to the proper people object.

在应用程序的次要位置中,有一个用于添加朋友的表单。该表单接受 firstName 和 lastName,然后带有 name 字段的 POST 也用于引用正确的 people 对象。

What I'm having a hard time doing is creating a new friend object and then "pushing" it into the friends array.

我很难做的是创建一个新的朋友对象,然后将它“推送”到朋友数组中。

I know that when I do this via the mongo console I use the update function with $push as my second argument after the lookup criteria, but I can't seem to find the appropriate way to get mongoose to do this.

我知道当我通过 mongo 控制台执行此操作时,我使用带有 $push 的更新函数作为查找标准之后的第二个参数,但我似乎找不到让 mongoose 执行此操作的适当方法。

db.people.update({name: "John"}, {$push: {friends: {firstName: "Harry", lastName: "Potter"}}});

UPDATE:So, Adrian's answer was very helpful. The following is what I did in order to accomplish my goal.

更新:所以,阿德里安的回答非常有帮助。以下是我为实现目标所做的工作。

in my app.js file, I set a temporary route using

在我的 app.js 文件中,我使用设置了一个临时路由

app.get('/addfriend', users.addFriend);

where in my users.js file I have

在我的 users.js 文件中我有

exports.addFriend = function (req, res, next)
{
var friend = {"firstName": req.body.fName, "lastName": req.body.lName};
Users.findOneAndUpdate({name: req.user.name}, {$push: {friends: friend}});
};

回答by Adrian Schneider

Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };

假设, var friend = { firstName: 'Harry', lastName: 'Potter' };

There are two options you have:

您有两种选择:

Update the model in-memory, and save (plain javascript array.push):

更新内存中的模型,并保存(普通的 javascript array.push):

person.friends.push(friend);
person.save(done);

or

或者

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

我总是尽可能地尝试第一个选项,因为它会尊重猫鼬给你的更多好处(钩子、验证等)。

However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

但是,如果您正在进行大量并发写入,则会遇到竞争条件,最终会出现令人讨厌的版本错误,从而阻止您每次都替换整个模型并失去您添加的前一个朋友。所以只有在绝对必要时才去前者。

回答by Parth Raval

The $pushoperator appends a specified value to an array.

$推操作者附加一个指定值的数组。

{ $push: { <field1>: <value1>, ... } }

$pushadds the array field with the value as its element.

$push添加以该值作为其元素的数组字段。

Above answer fulfils all the requirements, but I got it working by doing the following

以上答案满足所有要求,但我通过执行以下操作使其工作

var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
Friend.findOneAndUpdate(
   { _id: req.body.id }, 
   { $push: { friends: objFriends  } },
  function (error, success) {
        if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });
)

回答by KARTHIKEYAN.A

Use $pushto update document and insert new value inside an array.

使用$push以更新文档和插入内部数组新的价值。

find:

找:

db.getCollection('noti').find({})

result for find:

查找结果:

{
    "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
    "count" : 1.0,
    "color" : "green",
    "icon" : "circle",
    "graph" : [ 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 2.0
        }
    ],
    "name" : "online visitor",
    "read" : false,
    "date" : ISODate("2018-10-12T08:57:20.853Z"),
    "__v" : 0.0
}

update:

更新:

db.getCollection('noti').findOneAndUpdate(
   { _id: ObjectId("5bc061f05a4c0511a9252e88") }, 
   { $push: { 
             graph: {
               "date" : ISODate("2018-10-24T08:55:13.331Z"),
               "count" : 3.0
               }  
           } 
   })

result for update:

更新结果:

{
    "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
    "count" : 1.0,
    "color" : "green",
    "icon" : "circle",
    "graph" : [ 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 2.0
        }, 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 3.0
        }
    ],
    "name" : "online visitor",
    "read" : false,
    "date" : ISODate("2018-10-12T08:57:20.853Z"),
    "__v" : 0.0
}

回答by Felipe Toledo

An easy way to do that is to use the following:

一种简单的方法是使用以下方法:

var John = people.findOne({name: "John"});
John.friends.push({firstName: "Harry", lastName: "Potter"});
John.save();

回答by Prathamesh More

In my case, I did this

就我而言,我这样做了

  const eventId = event.id;
  User.findByIdAndUpdate(id, { $push: { createdEvents: eventId } }).exec();

回答by theRealSheng

I ran into this issue as well. My fix was to create a child schema. See below for an example for your models.

我也遇到了这个问题。我的解决方法是创建一个子模式。有关您的模型的示例,请参见下文。

---- Person model

---- 人物模型

const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema   = mongoose.Schema;

const productSchema = new Schema({
  friends    : [SingleFriend.schema]
});

module.exports = mongoose.model('Person', personSchema);

***Important: SingleFriend.schema -> make sure to use lowercase for schema

***重要:SingleFriend.schema -> 确保对架构使用小写

--- Child schema

--- 子模式

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const SingleFriendSchema = new Schema({
  Name: String
});

module.exports = mongoose.model('SingleFriend', SingleFriendSchema);