简体   繁体   English

如何使用 mongoose 添加到这个架构数组?

[英]How can I add to this schema array with mongoose?

Here's the user schema and the part I want to update is ToDo under User.js (further down).这是用户架构,我要更新的部分是 User.js 下的 ToDo(进一步向下)。 I am attempting to add new data to an array within the db.我正在尝试向数据库中的数组添加新数据。

data.js数据.js

app.post("/data", loggedIn, async (req, res) => {
  console.log(req.body.content);
  let content = { content: req.body.content };
  User.update({ _id: req.user._id }, { $set: req.body }, function (err, user) {
    if (err) console.log(err);
    if (!content) {
      req.flash("error", "One or more fields are empty");
      return res.redirect("/");
    }
    user.ToDo.push(content);
    res.redirect("/main");
  });
});

User.js用户.js

  new mongoose.Schema({
    email: String,
    passwordHash: String,
    ToDo: {
      type: [],
    },
    date: {
      type: Date,
      default: Date.now,
    },
  })

Originally I was trying the .push() attribute, but I get the error:最初我尝试使用 .push() 属性,但出现错误:

 user.ToDo.push(content); ^

TypeError: Cannot read property 'push' of undefined类型错误:无法读取未定义的属性“推送”

First of all, your problem is the callback is not the user.首先,您的问题是回调不是用户。 When you use update the callback is something like this:当您使用update ,回调是这样的:

{ n: 1, nModified: 1, ok: 1 }

This is why the error is thrown.这就是抛出错误的原因。

Also I recommend specify the array value, something like this:我还建议指定数组值,如下所示:

ToDo: {
  type: [String],
}

The second recommendation is to do all you can into mongo query.第二个建议是尽你所能进入mongo查询。 If you can use a query to push the object, do this instead of store the object into memory, push using JS function and save again the object into DB.如果您可以使用查询来推送对象,请执行此操作而不是将对象存储到内存中,使用 JS 函数push并再次将对象保存到数据库中。

Of course you can do that, but I think is worse.当然你可以这样做,但我认为更糟。

Now, knowing this, if you only want to add a value into an array, try this query:现在,知道了这一点,如果您只想将一个值添加到数组中,请尝试以下查询:

var update = await model.updateOne({
  "email": "email"
},
{
  "$push": {
    "ToDo": "new value"
  }
})

Check the example here检查这里的例子

You are using $set to your object, so you are creating a new object with new values.您正在对您的对象使用$set ,因此您正在创建一个具有新值的新对象。

Check here how $set works.在这里查看$set是如何工作的。

If fields no exists, will be added, otherwise are updated.如果字段不存在,将被添加,否则被更新。 If you only want to add an element into an array from a specified field, you should $push into the field.如果只想从指定字段向数组中添加元素,则应$push到该字段中。

Following your code, maybe you wanted to do something similar to this:按照您的代码,也许您想做类似的事情:

model.findOne({ "email": "email" }, async function (err, user) {
  //Here, user is the object user
  user.ToDo.push("value")
  user.save()
})

As I said before, that works, but is better do in a query.正如我之前所说,这可行,但最好在查询中进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM