通过ID推送到猫鼬数组没有获得ID

时间:2020-04-02 03:53:19

标签: javascript node.js mongodb mongoose

我试图将订阅的类对象添加到我的mongodb中,但是,当我将新的订阅的类推入数据库时​​,由于没有获得用户_id,它无法正常工作。

到目前为止,我已经尝试了这段代码以及诸如findone之类的其他东西

const userSchema = new mongoose.Schema({
    email: String,
    password: String,
    secret: String,
    classes: [String]
});

const userModel = mongoose.model("Class", userSchema)

const newClass = req.body.subClass;
const id = req.user.id
    userModel.findById(id, function (err, user) {
        if (user) {
            console.log(user)
            db.users.update(
                { _id: id },
                { $push: { classes: newClass } }
            )
        } else {
            console.log(err)
        }
    })

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:0)

我可以建议

  1. 将更新更改为findOneAndUpdate的目的是既处理“单一”文档上的更新语句,又检索该“单一”文档的内容。
  2. 在传递id之前,将其转换为ObjectId
  3. 将(db.users.update)数据库更改为userModel
const mongoose = require('mongoose'); 
const ObjectId = mongoose.Types.ObjectId;
userModel.findOneAndUpdate(
  { _id: new ObjectId(id) },
  { $push: { classes: newClass  } },
  { upsert: false, new: true }, // upsert looks to find a Message with that id and if it doesn't exist creates the Message if argument is true 
);

希望会帮助您

运行此文件节点index.js并在此帮助下更改代码!

// index.js
const mongoose = require('mongoose');
const ObjectId = mongoose.Types.ObjectId;
const mongoDB = 'mongodb://127.0.0.1/test';
mongoose.connect(mongoDB, { useUnifiedTopology: true, useNewUrlParser: true,useFindAndModify: false });

const userSchema = new mongoose.Schema({
    email: String,
    password: String,
    secret: String,
    classes: [String]
});

(async function  createAndUpdate(){
    // create user
    const userModel = mongoose.model("Class", userSchema);
    const newUser = new userModel({
        email: 'user@gmail.com',
        password: 'password',
        secret: 'secret',
        classes: 'classes1'
    });
    await newUser.save();

    // update user
    const newClass = 'new-classes2';
    const id = newUser._id;
    await userModel.findOneAndUpdate(
        { _id: new ObjectId(id) },
        { $push: { classes: newClass  } },
        { upsert: false }
    );
})();