Javascript 编辑数组中对象的值

Javascript 编辑数组中对象的值,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我有一个目标: { "_id" : ObjectId("5a8d83d5d5048f1c9ae877a8"), "websites" : [ "", "", "" ], "keys" : [ { "_id" : ObjectId("5a8d83d5d5048f1c9ae877af"), "name" : "Google",

我有一个目标:

{
  "_id" : ObjectId("5a8d83d5d5048f1c9ae877a8"),
  "websites" : [
          "",
          "",
          ""
  ],
  "keys" : [
          {
                  "_id" : ObjectId("5a8d83d5d5048f1c9ae877af"),
                  "name" : "Google",
                  "value" : ""
          },
          {
                  "_id" : ObjectId("5a8d83d5d5048f1c9ae877ae"),
                  "name" : "Built With",
                  "value" : ""
          },
          {
                  "_id" : ObjectId("5a8d83d5d5048f1c9ae877ad"),
                  "name" : "Check Host",
                  "value" : ""
          },
          {
                  "_id" : ObjectId("5a8d83d5d5048f1c9ae877ac"),
                  "name" : "Alexa",
                  "value" : ""
          },
          {
                  "_id" : ObjectId("5a8d83d5d5048f1c9ae877ab"),
                  "name" : "Facebook",
                  "value" : ""
          },
          {
                  "_id" : ObjectId("5a8d83d5d5048f1c9ae877aa"),
                  "name" : "Instagram",
                  "value" : ""
          },
          {
                  "_id" : ObjectId("5a8d83d5d5048f1c9ae877a9"),
                  "name" : "Moz",
                  "value" : ""
          }
  ],
  "username" : "admin@admin",
  "isPremium" : false,
  "accType" : "admin",
  "hash" : "very long hash",
  "salt" : "long salt",
}
现在。使用NodeExpress和Mongoose,我需要能够编辑
数组中每个对象的
字段

我的
GET
操作如下:

// GET: /websites/:_id - show edit form
router.get('/keys/edit/:_id', isAdmin, function(req, res, next) {
  // console.log('tada');
  // console.log(req.params._id);

  Account.findOne({ _id: req.user._id }, function(err, user) {
    var selectedKey = findById(user.keys, req.params._id);
    // var keys = user.keys.findOne(req.params._id);
    console.log(selectedKey);
    res.render('admin/edit', {
      title: 'Edit websites',
      user: req.user,
      value: selectedKey.value,
    });
  });
});
应用程序的工作原理是:管理员登录。他查看所有用户并选择要修改的用户,然后管理员查看所有密钥。我会附上截图来更清楚地解释它

现在。我想我知道我需要做什么,但我不知道如何把它翻译成代码

我想我需要:找到数组元素的索引,就像在GET请求中一样,用发布的值更新该值。我想我需要在数组中找到索引

但正如我所说,我不知道该怎么做

我的帖子现在看起来像这样:

// POST: /keys/edit/_id - save updates
router.post('/keys/edit/:_id', isAdmin, function(req, res, next) {
  var p = req.params;
  var b = req.body;
  Account.findOne({ _id: req.user._id }, function(err, user) {
    var selectedKey = findById(user.keys, req.params._id);
    // console.log('Key value: ' + req.body.keyValue);
    // console.log('Selected key: ' + selectedKey);
    console.log('id:' + req.params._id);
    if (err) {
      console.log(err);
    } else {
      console.log(user);
      user.keys.set(req.params._id, req.body.keyValue);
      user.save(err => {
        if (err) {
          console.log(err);
        } else {
          console.log('all good');
        }
        res.redirect('/admin');
      });
    }
  });
编辑:所以我在这方面做了一段时间,我发现了这一点。我使用的是正确的用户,我正在抓取里面的keys数组,但是我不知道如何在数组中找到对象的id,我需要编辑哪个(对象)

有很多嵌套,这可能会导致一些问题

编辑2:我正在攻击我的帐户模型。早些时候就忘了。对不起

var mongoose = require('mongoose');

var website = require('./website');

var plm = require('passport-local-mongoose');

    var accountSchema = new mongoose.Schema({
      isPremium: Boolean,
      accType: String,
      websites: [],
      keys: [
        { name: String, value: String },
        { name: String, value: String },
        { name: String, value: String },
        { name: String, value: String },
        { name: String, value: String },
        { name: String, value: String },
        { name: String, value: String },
      ],
    });

accountSchema.plugin(plm);

module.exports = mongoose.model('Account', accountSchema);

我并不完全清楚你想做什么,但我可以推断你想做以下事情:

您有一个对象,该对象有一个
数组
,其形状如下:

{
    "_id" : ObjectId("5a8d83d5d5048f1c9ae877af"),
    "name" : "Google",
    "value" : ""
}
从示例对象判断,我推断模式的定义如下:

const mongoose = require('mongoose')

const definition = {
  websites: [String],
  keys: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Key'
  }]
}

const accountSchema = new mongoose.Schema(definition)

module.exports = mongoose.model('Account', topicSchema)
根据路由的外观,您希望在给定索引处更新/编辑该对象:
keys[i]
。如果是这种情况,则无需手动遍历阵列,直接更新模型:

const Key = require('./path/to/models/Key')

router.post('/keys/edit/:id', async (req, res) => {
    const { keyValue } = req.body
    const conditions = { _id: req.params.id }
    await Key.findOneAndUpdate({ id }, { value: keyValue }).exec()
    res.status(201).json()
})

当您查询父模型时,将更新数组中的项。

您可以使用运算符以原子方式执行更新

您可以从
键中包含字段(
\u id
),以定位元素的索引,并在更新部分中将占位符(
$
)替换为查询部分中找到的索引,以设置
键中的

 router.post('/keys/edit/:_id', isAdmin, function(req, res, next) {
  var p = req.params;
  var b = req.body;
  Account.findOneAndUpdate(
   {_id: req.user._id,'keys._id':req.params._id }, 
   {$set:{'keys.$.value':req.body.keyValue}},
   {new: true}, 
   function(err, account) {}
);

什么是ObjectId()
,它是在哪里定义的?我有两个级别的ObjectId()。第一个是顶级用户id,第二个是数组中嵌套的对象键。两者都是在用户注册期间定义的mongo服务器版本是什么?我使用的是mlab。我不知道。我该怎么检查呢?我的错。我更新了问题。它的定义不同。请看一看。除非创建一个关键模型是更好的方法。胡说!谢谢你,伙计!我需要深入了解这些操作员。你能画一张粗略的图片让我知道将来要搜索什么吗。搜索文档。寻找,然后。