Mongoose将新字段添加到集合(Node.js)

时间:2017-01-19 23:15:04

标签: node.js mongodb express mongoose

我有一个架构:

var userSchema = new Schema({
  name: String,
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  admin: Boolean,
  created_at: Date,
  updated_at: Date
});

假设我使用此架构制作了100 Users

现在我想更改架构:

var userSchema = new Schema({
  name: String,
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  admin: Boolean,
  created_at: Date,
  friends: [Schema.Types.ObjectId], //the new addition
  updated_at: Date
});

我需要所有新Users来拥有此字段。我还希望现有的所有100个Users都拥有此字段。我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

使用客户端应用程序或终端中的查询界面,您可以执行以下操作:

db.users.updateMany({ 
  $set: { "friends" : [] } 
});

这是docs reference.

答案 1 :(得分:1)

您可以使用Mongoose Model.update更新集合中的所有文档。

User.update({}, { friends: [] }, { multi: true }, function (err, raw) {
  if (err) return handleError(err);
  console.log('The raw response from Mongo was ', raw);
});

如果集合很大,我不建议在生产中使用它,因为它是一个繁重的操作。但在你的情况下应该没问题。

答案 2 :(得分:0)

这对我不起作用:x

这是我的代码

let test = await this.client.db.users.updateMany({
    $set: { "roles" : [] }
});

和输出

{ ok: 0, n: 0, nModified: 0 }

我不知道该怎么办,我尝试了很多事情,但是它不起作用:'(

编辑:我发现了,这是我的代码

await this.client.db.users.updateMany({ }, [ {$set : { "roles": []} } ]);