Mongoose:分配“字符串数组”类型的字段 [英] Mongoose: assign field of type 'array of Strings'

查看:536
本文介绍了Mongoose:分配“字符串数组”类型的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var user = new Schema({
/ /其他字段...

电子邮件:[String]
});

更新此字段时遇到麻烦。说,email1和email2是我从视图中获得的值:

这样做很好:

 用户。 emails = [email1,email2]; 
user.save();
//字段更新,所有好的

这不是:

  user.emails [0] = email1; 
user.emails [1] = email2;
user.save(function(err,savedUser){
console.log(savedUser.emails); //更新的数组[email1,email2]
//但是如果我现在检索该用户,电子邮件字段将不会有以上更改。
});

但奇怪的是,这有效:

  user.emails = [email1]; 
user.emails [1] = email2;
user.save();
// user.emails == [email1,email2];

任何人都可以解释为什么会发生这种情况?

解决方案

没有很好的记录,但是当操作数组字段时,您需要确保您触发Mongoose的字段更改检测,以便知道该数组已被修改,并且需要保存。





通过其方括号中的索引直接设置数组元素不会将其修改,因此您必须手动使用 markModified

  user.emails [0] = email1; 
user.markModified('emails');

或者您可以一次性使用 set Mongoose数组的方法:

  user.emails.set(0,email1); 

覆盖整个数组字段也会触发它,这就是为什么这适用于你:

  user.emails = [email1,email2]; 

以及

  user.emails = [email1]; 
user.emails [1] = email2;

这意味着这也有效:

  user.emails = []; 
user.emails [0] = email1;
user.emails [1] = email2;


I'm using array of Strings to save emails:

var user = new Schema({
  // other fields...

  emails: [String]
});

Have troubles updating this field. Say, email1 and email2 are values I receive from the view:
This works well:

user.emails = [email1, email2];
user.save();
// fields are updated, all good

And this doesn't:

user.emails[0] = email1;
user.emails[1] = email2;
user.save(function(err, savedUser) {
  console.log(savedUser.emails); // updated array [email1, email2]
  // but if I retrieve now the user, the 'emails' field will not have above changes.
});

But, strangely, this works:

user.emails = [email1];
user.emails[1] = email2;
user.save();
// user.emails == [email1, email2];

Can anybody explain why this is happening?

解决方案

It's not well documented, but when manipulating array fields you need to make sure that you're triggering Mongoose's field change detection so that it knows that the array has been modified and needs to be saved.

Directly setting an array element via its index in square brackets doesn't mark it modified so you have to manually flag it using markModified:

user.emails[0] = email1;
user.markModified('emails');

Or you can do it in one go, using the set method of the Mongoose array:

user.emails.set(0, email1);

Overwriting the entire array field also triggers it which is why this works for you:

user.emails = [email1, email2];

as well as:

user.emails = [email1];
user.emails[1] = email2;

Which means that this also works:

user.emails = [];
user.emails[0] = email1;
user.emails[1] = email2;

这篇关于Mongoose:分配“字符串数组”类型的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆