【问题标题】:Update a document collection in MongoDB using Node.js使用 Node.js 更新 MongoDB 中的文档集合
【发布时间】:2014-11-19 20:21:30
【问题描述】:

我正在使用类似 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 存储在以下内容和关注者字段中。

我不确定如何插入和更新关注者和关注者集合。 我尝试使用“更新”,但每次都会覆盖。 然后尝试推送,但没有帮助。

请帮帮我。

提前致谢。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在您的情况下,我将使用运算符 $addToSet 将值附加到数组(如果它不存在)。

    mongodb shell 中的示例

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

    【讨论】:

    • 如何从集合中删除特定文档?
    • 试试 $pullAll 命令。从数组中删除所有出现的对象。查看手册。
    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 2014-10-17
    • 2020-03-27
    相关资源
    最近更新 更多