将元素推送到猫鼬中的数组 [英] Push element to array in mongoose

查看:52
本文介绍了将元素推送到猫鼬中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用猫鼬将元素推到数组中.我正在用update和$ push来做.但是它不会在数据库中更新它.这是我的代码. route.js:

I am trying to push an element to an array in mongoose. I am doing it with update and $push. But it is not updating it in the database. This is my code. routes.js:

    var Chooser = require('../chooser');

    var appRouter = function(app) {

    app.put("/chooser/:id", function(req, res) {
    console.log("ID: ", req.params.id);
    if (!req.body.toFollow) {
        return res.send({"status": "error", "message": "The account that you want to follow is needed"});
    }
    else {
        console.log("Cuenta: ", req.body.toFollow);
        Chooser.update({_id: req.params.id}, {$push: {accounts: {"name": "foo", "idAccount": 123456}}});
        return res.send({"status": "ok"});
    }

  });
}

这是我的猫鼬模式. Chooser.js:

This is my mongoose schema. Chooser.js:

var mongoose = require('mongoose');

var chooserSchema = mongoose.Schema({
_id: Number,
accounts: [{name: String, idAccount: Number}]
}, { _id: false });

var Chooser = mongoose.model('Chooser', chooserSchema);

module.exports = Chooser;

推荐答案

据我所知,您必须执行以下操作.

As far as I know, you have to do as below.

Model.findAndUpdate({_id: 'your_id'}, 
                    {$push: {'your_array_field': 
                    {"name": "foo","idAccount": 123456}}}, 
                    {new: true}, (err, result) => {
                    // Rest of the action goes here
                   })

这篇关于将元素推送到猫鼬中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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