使用带有nodejs和mongo / mongoose的护照。
我将出勤记录存储在一个集合中,该集合使用req.user.id作为查找,将出勤记录与注册用户联系起来。关键字段称为“userId”。
在尝试加入时,我了解到用户集合中的_id不是字符串类型。我一直试图解决这个问题。我最新的是在将req.user.id转换为ObjectId()之后尝试保存出勤记录。不过,没有运气。看起来userId仍然保存为字符串。我怎样才能让这个加入工作?
router.post('/', ensureAuthenticated, function(req, res){
var query = { userId: req.user.id };
var update = {
userId: new ObjectId(req.user.id), // This is where I need to save
response: req.body.inOrOut,
notes: req.body.notes
};
// Upsert
var options = { upsert: true };
// Use mongoose to save via upsert.
RSVP.findOneAndUpdate( query, update, options, function( err, doc ) {
if ( err ) throw err;
});
这是加入:
RSVP.aggregate([{
$lookup: {
from: "users", // collection name in db
localField: "userId",
foreignField: "_id",
as: "user"
}
}
]).exec( (err, rsvpList) => {
if (err) throw err;
console.log(rsvpList);
});
编辑:
我刚刚意识到 rsvps 的mongoose架构仍然以 userId 作为字符串。我改变如下:
let mongoose = require('mongoose');
//let ObjectId = require('mongodb').ObjectId;
// RSVP Schema
var RSVPSchema = mongoose.Schema({
userId: {
//type: String,
type: mongoose.Schema.Types.ObjectId,
index:true
},
response: {
type: String
},
notes: {
type: String
},
});
var RSVP = module.exports = mongoose.model('RSVP', RSVPSchema);
我的console.log:
console.log('rsvp: ' + rsvpList[0].user.toString());
显示[Object object]。我无法确定我的加入是否有效。如何测试 rsvpList [0] .user 以查看它是否包含已加入的用户?
答案 0 :(得分:0)
我很亲密。应该是:
console.log('rsvp: ' + rsvpList[0].user[0].name);