我有一个引用另一个对象的模式。
模型/ message.js
var moogoose = require('mongoose');
var Schema = moogoose.Schema;
var schema = new Schema({
.
user: {type: Schema.Types.ObjectId, ref: 'User'}
.
});
module.exports = moogoose.model('Message', schema);
假设user
是从数据库中提取的对象
我应该将user._id
或user
对象分配给消息模型的user
属性。我尝试了两种方法,它们产生的结果与_id
相同,作为用户属性的值。
var message = new Message({
user: user._id,
});
或:
var message = new Message({
user: user
});
答案 0 :(得分:2)
这是我使用的架构之一。
var mongoose=require('mongoose');
var config=require('./config'); //configuarations and APIS keys stored in this file
mongoose.connect(config.MONGO_URL, {server:{poolSize:10}});
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var users = new mongoose.Schema({
mobile: { type: String, unique: true },
hash: String,
location:{ type:[Number, Number], index:'2d'},
locName: String,
created_at: Number,
image: {type: String, default: 'NONE'},
role: {type: String, default: 'USER'},
name: {type: String, default: 'NONE'},
});
exports.users = mongoose.model('users', users);
var comments = new mongoose.Schema({
uid: { ObjectId, ref: 'users'},
liked_by: {type: [ObjectId], default: []},
like_count: {type: Number, default: 0},
created_at: Number
});
comments.index({spark_id:1, created_at:1});
exports.comments = mongoose.model('comments', comments);
这是其中一项功能
dbase.comments.find({uid: req.body.user._id, function(err, response){
if(!err){
//do what you want
}else{
//handle error
}
}).sort({created_at: -1}).skip(count).limit(50).lean();