簡體   English   中英

使用Node.js更新MongoDB中的文檔集合

[英]Update a document collection in MongoDB using Node.js

我正在工作一個Twitter的關注模型,其用戶架構如下。

var UserSchema = new Schema({ 
    username: {type: String, match: /^[a-zA-Z0-9_]+$/, unique: true}, 
    email: { type: String, unique: true }, 
    password: String, 
    followings : [{ type: ObjectId, ref: 'User' }],
    followers : [{ type: ObjectId, ref: 'User' }] });

我只需要在以下和關注者字段中存儲用戶的ObjectId。

我不確定如何插入和更新以下和關注者集合。 我嘗試使用“更新”,但每次都會覆蓋。 然后嘗試推送,但無濟於事。

請幫我。

提前致謝。

在您的情況下,我將使用$ addToSet運算符,如果該值不存在,它將向該數組追加一個值。

mongodb shell中的示例

db.userSchema.update({"username" : USERNAME}, { "$addToSet" : { "followers" : ObjectId}})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM