Я пытаюсь добавить сообщение в коллекцию пользователей после того, как пользователь был создан с пустыми сообщениями. Я пытался с populate без успеха .. любая помощь очень ценится.
// Post Model
const mongoose = require('mongoose');
const { Schema } = mongoose;
const UserModel = require('./user-model');
let PostSchema = new Schema({
author: {
ref: 'users',
type: Schema.Types.ObjectId
},
content: String,
description: String,
date: {
default: new Date(),
type: Date
},
title: String,
updatedAt: {
default: new Date(),
type: Date
}
});
let PostModel = mongoose.model('posts', PostSchema);
module.exports = PostModel;
// User Model
const mongoose = require('mongoose');
const { Schema } = mongoose;
const PostModel = require('./post-model');
let UserSchema = new Schema({
name: {
type: String
},
email: {
lowercase: true,
type: String,
trim: true,
unique: true
},
password: {
type: String,
},
postList: [{
ref: 'posts',
type: Schema.Types.ObjectId
}],
});
const UserModel = mongoose.model('users', UserSchema);
module.exports = UserModel;
// save post controller
exports.savePost = (request, response, next) => {
let { author, description, title } = request.body;
let post = new PostModel({ author, description, title }).save();
UserModel.findById(author)
.then((user) => {
user.postList.push(post);
// Still Fails
// How can i assign the post to the user ?
});
}
Есть ли какой-либо способ сделать это другое, чем толкать или заполнять ?
Для решения этой проблемы я предпочитаю использовать $push of mongo
Вы должны следовать этому процессу, чтобы сохранить успешно
можете попробовать это
Это то, что я сделал, и это сработало в конце концов. Я не знаю, если это правильное решение, но это работает.