我试图将订阅的类对象添加到我的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)
}
})
任何帮助将不胜感激:)
答案 0 :(得分:0)
我可以建议
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 }
);
})();