IT박스

몽구스를 통해 아이템을 몽고 배열로 푸시

itboxs 2020. 7. 7. 07:56
반응형

몽구스를 통해 아이템을 몽고 배열로 푸시


나는 대답을 찾기 위해 약간을 닦았지만, 내가 따르는 것을 설명하기 위해 올바른 단어를 잃어 버릴 것이라고 확신합니다.

기본적으로 'people'라는 mongodb 컬렉션이 있습니다. 해당 컬렉션의 스키마는 다음과 같습니다.

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

이제 데이터베이스에 연결하고 빈 friends 배열로 'people'을 성공적으로 만드는 매우 기본적인 Express 응용 프로그램이 있습니다.

응용 프로그램의 보조 장소에는 친구를 추가 할 수있는 양식이 있습니다. 양식은 firstName과 lastName을 취한 다음 적절한 사람 오브젝트를 참조하기 위해 name 필드를 가진 POST를 취합니다.

내가 겪고있는 일은 새로운 친구 개체를 만든 다음 그것을 friends 배열에 "푸시"하는 것입니다.

mongo 콘솔을 통해이 작업을 수행 할 때 조회 기준 후 두 번째 인수로 $ push와 함께 업데이트 기능을 사용하지만 mongoose 가이를 수행하는 적절한 방법을 찾지 못하는 것 같습니다.

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

업데이트 : Adrian의 답변은 매우 도움이되었습니다. 다음은 목표를 달성하기 위해 내가 한 일입니다.

내 app.js 파일에서 다음을 사용하여 임시 경로를 설정했습니다.

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

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

가정의 방, var friend = { firstName: 'Harry', lastName: 'Potter' };

두 가지 옵션이 있습니다.

모델 내 메모리를 업데이트하고 저장하십시오 (일반 자바 스크립트 array.push).

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

또는

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

몽구스가 제공하는 많은 이점 (후크, 유효성 검사 등)을 존중하기 때문에 가능한 한 항상 첫 번째 옵션을 찾으려고 노력합니다.

그러나 동시 쓰기를 많이 수행하는 경우 매번 전체 모델을 교체하지 않고 추가 한 이전 친구를 잃지 않도록 불쾌한 버전 오류가 발생하는 경쟁 조건에 부딪치게됩니다. 절대적으로 필요한 경우에만 전자에게 가십시오.


$ 누름 조작 배열로 지정된 값을 추가한다.

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

$ push 는 값을 요소로하여 배열 필드를 추가합니다.

위의 답변은 모든 요구 사항을 충족하지만 다음을 수행하여 작동시킵니다.

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

$push문서를 업데이트하고 배열 안에 새로운 값을 삽입하는 데 사용 합니다.

찾기:

db.getCollection('noti').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
}

최신 정보:

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

업데이트 결과 :

{
    "_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
}

이를 수행하는 쉬운 방법은 다음을 사용하는 것입니다.

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

나는이 문제에 부딪쳤다. 내 수정은 자식 스키마를 만드는 것이 었습니다. 모델의 예는 아래를 참조하십시오.

---- 사람 모델

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

--- Child schema

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

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

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

참고URL : https://stackoverflow.com/questions/33049707/push-items-into-mongo-array-via-mongoose

반응형